<?php
namespace Admin\Controller;
require_once './ThinkPHP/Library/Vendor/yiwei/autoload.php';
use BarcodeBakery\Common\BCGColor;
use BarcodeBakery\Common\BCGDrawing;
use BarcodeBakery\Common\BCGFontFile;
use BarcodeBakery\Barcode\BCGcode128;

use Admin\Logic\OrderLogic;
use Think\AjaxPage;
use Think\AjaxPage2;
use Think\Db;
use Think\Model;
use Think\Page;
use Think\Page2;
use WXAPI\Controller\PayController;

class OrderController extends BaseController {
    public  $order_status;
    public  $shipping_status;
    public  $pay_status;
    public  $z;
    /*
     * 初始化操作
     */
    public function _initialize() {
        parent::_initialize();
        C('TOKEN_ON',false); // 关闭表单令牌验证
        // 订单 支付 发货状态
        $this->order_status = C('ORDER_STATUS');
        $this->pay_status = C('PAY_STATUS');
        $this->shipping_status = C('SHIPPING_STATUS');
        $this->assign('order_status',$this->order_status);
        $this->assign('pay_status',$this->pay_status);
        $this->assign('shipping_status',$this->shipping_status);
        $this->z =  '';
    }

    //   public function cs(){
    // $orderlisit=M('return_goods')->where('addtime>1672730135 and addtime<1675757517')->select();
    // foreach($orderlisit as $v){
    // 	M('return_goods')->where('id='.$v['id'])->setField([
    // 		'member_goods_price'=>M('order_goods')->where('order_id='.$v['order_id'].' and spec_key="'.$v['spec_key'].'"')->getField('member_goods_price')
    // 	]);
    // }
    //   }
    public function cs(){ //重写订单价格
        $orderlisit=M('order')->where('add_time>1673884476')->select();
        foreach($orderlisit as $v){
            $order_goods=M('order_goods')->where('order_id='.$v['order_id'])->select();
            $pd_price=0;
            foreach($order_goods as $vs){
                $pd_price+=($vs['member_goods_price']+$vs['yijia'])*$vs['goods_num'];
            }
            if($v['order_amount']-$pd_price>1){
                echo $v['order_sn'].'<br/>';
            }
        }
    }

	
    /*
     *订单首页
     */
    public function index(){
        $begin = date('Y-m-d 00:00',(time()-30*60*60*24));//30天前
        $end = date('Y-m-d 23:59',strtotime('+1 days'));
        $this->assign('timegap',$begin.' - '.$end);
        $this->assign('fenbu_list',$this->fenbu_list);
        $this->display();
    }
    /*
     *Ajax首页
     */
    public function ajaxindex(){
        $orderLogic = new OrderLogic();
        $timegap = I('timegap');
        $ku_status = I('ku_status');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
            $daysDiff = floor(abs($begin - $end) / (60 * 60 * 24));
            if($daysDiff > 180){
                exit(json_encode(['code'=>0,'msg'=>'查询时间区间不能超过半年，请半年半年查','data'=>[]]));
            }
        }else{
            exit(json_encode(['code'=>0,'msg'=>'查询时间不能未空','data'=>[]]));
        }
        // 搜索条件

        $condition = array();
        $order_type=I('order_type');
        if($order_type){
            if($order_type=='1'){
                $condition['a.dai_type'] = 0;
            }elseif($order_type=='2'){
                $condition['a.dai_type'] = 1;
            }
        }
        if(!empty(session('fenbu_id'))){
            $condition['a.ufenbu_id']=session('fenbu_id');
        }
        // I('consignee') && $condition['_string'] = ' (consignee like "%'.I('consignee').'%") OR (b.company like "%'.I('consignee').'%") OR (store_name like "%'.I('consignee').'%")  OR (b.mobile like "%'.I('consignee').'%")';
         I('consignee') && $condition['_string'] = ' (a.consignee like "'.I('consignee').'%") OR (b.company like "%'.I('consignee').'%") ';
        if($begin && $end){
            $condition['add_time'] = array('between',"$begin,$end");
        }
        
//        if(I('consignee')){
//            $condition['a.consignee'] = ['like',I('consignee').'%'];
//        }
        if(I('company')){
            $condition['b.company'] = ['like',I('company').'%'];
        }
        if(I('same_order')){
            $condition['a.same_order'] = I('same_order');
        }
        if(I('store_name')){
            $condition['c.store_name'] = ['like',I('store_name').'%'];
        }
        if(I('mobile')){
            $condition['b.mobile'] = ['like',I('mobile').'%'];
        }
        
        //$condition['order_prom_type'] = 0;
        if(I('order_sn') ){
            $subQuery_orderIds = M()->query('select order_id from ty_order WHERE LOCATE('.I('order_sn').',order_sn) > 0');
            foreach ($subQuery_orderIds as $item){
                $ids[] = $item['order_id'];
            }
            if($ids){
                $condition['a.order_id'] = ['in',join(',',$ids)];
            }else{
                $condition['a.order_id'] = 0;
            }

        }
        //I('order_sn') ? $condition['order_sn'] = array('like','%'.trim(I('order_sn')).'%') : false;


        I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
        I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
        I('pay_code') != '' ? $condition['pay_code'] = I('pay_code') : false;
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;
        I('fast_flag') != '' ? $condition['b.fast_flag'] = I('fast_flag') : false;
        I('biaoshi_xian') ? $condition['b.biaoshi_xian'] = I('biaoshi_xian') : false;
        I('pda_qdzt') ? $condition['a.pda_qdzt'] = I('pda_qdzt') : false;
        I('driver') ? $condition['e.nick_name'] = I('driver') : false;
        I('goods_name') ? $condition3['goods_name|goods_id'] = array('like','%'.trim(I('goods_name')).'%') : false;

        if($ku_status){
            switch ($ku_status){
                case 1:
                    $condition['a.ruku_count'] = ['eq',0];
                    break;
                case 2:
                    $condition['a.ruku_count'] = ['gt',0];
                    $condition['a.chuku_count'] = ['eq',0];
                    break;
                case 3:
                    $condition['a.chuku_count'] = ['gt',0];
                    break;
            }
        }

        if($condition3){

            $subQuery2 = M('order_goods')->where($condition3)->getField('order_id',true); //查询订单号

            $duplicates = $subQuery2;
            $duplicates = $duplicates!=[] ? $duplicates : [0];
            $condition['a.order_id'] = ['in',join(',',$duplicates)];
        }

        // $condition['c.store_name'] = ['neq',''];
        // dump($condition);
        $sort_order = I('order_by','DESC').' '.I('sort');
        $count = M('order a')
            ->join('ty_users b ON a.user_id = b.user_id','LEFT')
            ->join('ty_store c ON a.store_id = c.store_id','LEFT')
            ->join('ty_users e ON a.driver_id = e.user_id','LEFT')
            ->where($condition)->count();
        $Page  = new AjaxPage($count,20);
        //  搜索条件下 分页赋值

        $show = $Page->show();
        //获取订单列表
        $orderList = $orderLogic->getOrderList($condition,$sort_order,$Page->firstRow,$Page->listRows);

        //获取主订单号
        foreach($orderList as $key=>$value){
            //去重复
            $goods = M('order_goods a')->field('a.*,b.original_img')
                ->join('ty_goods b ON a.goods_id = b.goods_id')
                ->where(array('a.order_id'=>$value['order_id']))
                ->select();
            $coupon = M('coupon')->where(['id'=>$value['coupon_id']])->getField('name');
            $coupon_store_id = M('coupon')->where(['id'=>$value['coupon_id']])->getField('store_id');

            if(!empty($coupon)){
                if($coupon_store_id != 0){
                    $orderList[$key]['coupon_name'] = '店铺：'.$coupon;
                }else{
                    $orderList[$key]['coupon_name'] = $coupon;
                }

            }else{
                $orderList[$key]['coupon_name'] = '';
            }
            $tuihuo=M('return_goods')->where('status <> 3 and order_id='.$value['order_id'])->select();$tuihuos=$tuihuo0=0;
            foreach($tuihuo as $vs){
                $tuihuo0+=\sanwei(($vs['member_goods_price']+$vs['yijia'])*$vs['goods_num']);
                $tuihuos+=\sanwei($vs['member_goods_price']*$vs['goods_num']-$vs['member_goods_price']*$vs['goods_num']*$vs['points']/100);
            }

            if($orderList[$key]['fast_flag'] && $orderList[$key]['shop_fast_flag']){
                $orderList[$key]['fast_text'] = '快线订单';
            }else{
                $orderList[$key]['fast_text'] = '';
            }
            $orderList[$key]["ruku"]=M('order_jian')->where('order_id='.$value['order_id'].' and '.$this->z.'status_r=1')->count();
            $orderList[$key]["chuku"]=M('order_jian')->where('order_id='.$value['order_id'].' and '.$this->z.'status_c=1')->count();
            $orderList[$key]["tuihuo0"]=$tuihuo0;$orderList[$key]["tuihuo"]=$tuihuos;
            $orderList[$key]["order_price"]=order_price($value['order_id']);
            $orderList[$key]["suoshu_name"]=M('fenbu')->where('fenbu_id='.$value['fenbu_id'])->getField('fenbu_name');
            $orderList[$key]["usuoshu_name"]=M('fenbu')->where('fenbu_id='.$value['ufenbu_id'])->getField('fenbu_name');
            $orderList[$key]["order_amount"]=($value['order_amount']+$value['yijia_heji']);
            foreach($goods as $keys=>$vs){
                $goods[$keys]['tuihuo_num']=M('return_goods')->where('status <> 3 and  order_id='.$value['order_id'].' and spec_key="'.$vs['spec_key'].'"')->sum('goods_num');
                if(empty($goods[$keys]['tuihuo_num'])){
                    $goods[$keys]['tuihuo_num'] = 0;
                }
                //if(session('fenbu_id')!=0){
                $goods[$keys]['member_goods_price']=$vs['member_goods_price']+$vs['yijia'];

                $spec_img = M('spec_image')->where(['spec_image_id'=>$vs['spec_key']])->getField('src');
                if($spec_img){
                    $goods[$keys]['original_img'] = C('MYOSS')['url2'].$spec_img;
                }else{
                    $goods[$keys]['original_img'] =  C('MYOSS')['url2'].$vs['original_img'];
                }

                //}
            }
            $orderList[$key]["g_list"]=$goods;

            $orderList[$key]["pay_name"]=M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>$value['pay_code']))->getField('name');

        }
    
        // echo json_encode($orderList);
        // dump($orderList);
        $store_list = M('store')->getField('store_id,store_name');
        $this->assign('store_list',$store_list);
        $this->assign('fenbu_list',$this->fenbu_list);
        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }

    /**
     * 配货订单
     * */
    public function distribution(){
        $begin = date('Y-m-d 00:00',(time()-30*60*60*24));//30天前
        $end = date('Y-m-d 23:59',strtotime('+1 days'));
        $this->assign('timegap',$begin.' - '.$end);
        $this->assign('fenbu_list',$this->fenbu_list);
        $this->display();
    }
    /*
   *Ajax首页
   */
    public function ajaxdistribution(){
        $orderLogic = new OrderLogic();
        $timegap = I('timegap');
        $ku_status = I('ku_status');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
            $daysDiff = floor(abs($begin - $end) / (60 * 60 * 24));
            if($daysDiff > 180){
                exit(json_encode(['code'=>0,'msg'=>'查询时间区间不能超过半年，请半年半年查','data'=>[]]));
            }
        }else{
            exit(json_encode(['code'=>0,'msg'=>'查询时间不能未空','data'=>[]]));
        }
        // 搜索条件

        $condition = array();
        if(!empty(session('fenbu_id'))){
            $condition['a.ufenbu_id']=session('fenbu_id');
        }
        I('consignee') && $condition['_string'] = ' (a.consignee like "'.I('consignee').'%") OR (b.company like "%'.I('consignee').'%") ';
        if($begin && $end){
            $condition['add_time'] = array('between',"$begin,$end");
        }
        if(I('company')){
            $condition['b.company'] = ['like',I('company').'%'];
        }
        if(I('store_name')){
            $condition['c.store_name'] = ['like',I('store_name').'%'];
        }
        if(I('mobile')){
            $condition['b.mobile'] = ['like',I('mobile').'%'];
        }
        if(I('order_sn') ){
            $subQuery_orderIds = M()->query('select order_id from ty_order WHERE LOCATE('.I('order_sn').',order_sn) > 0');
            foreach ($subQuery_orderIds as $item){
                $ids[] = $item['order_id'];
            }
            if($ids){
                $condition['a.order_id'] = ['in',join(',',$ids)];
            }else{
                $condition['a.order_id'] = 0;
            }

        }
        //I('order_sn') ? $condition['order_sn'] = array('like','%'.trim(I('order_sn')).'%') : false;


//        I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
        I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
        I('pay_code') != '' ? $condition['pay_code'] = I('pay_code') : false;
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;
        I('fast_flag') != '' ? $condition['b.fast_flag'] = I('fast_flag') : false;
        I('biaoshi_xian') ? $condition['b.biaoshi_xian'] = I('biaoshi_xian') : false;
        I('pda_qdzt') ? $condition['a.pda_qdzt'] = I('pda_qdzt') : false;
        I('driver') ? $condition['e.nick_name'] = I('driver') : false;
        I('goods_name') ? $condition3['goods_name|goods_id'] = array('like','%'.trim(I('goods_name')).'%') : false;
        $condition['order_status'] = 0;
        // $condition['jian_count'] = ['gt',0];
        // $condition['stock_up'] = 2;
        // if($ku_status){
        //     switch ($ku_status){
        //         case 1:
        //             $condition['a.ruku_count'] = ['eq',0];
        //             break;
        //         case 2:
        //             $condition['a.ruku_count'] = ['gt',0];
        //             $condition['a.chuku_count'] = ['eq',0];
        //             break;
        //         case 3:
        //             $condition['a.chuku_count'] = ['gt',0];
        //             break;
        //     }
        // }

        if($condition3){

            $subQuery2 = M('order_goods')->where($condition3)->getField('order_id',true); //查询订单号

            $duplicates = $subQuery2;
            $duplicates = $duplicates!=[] ? $duplicates : [0];
            $condition['a.order_id'] = ['in',join(',',$duplicates)];
        }

        // $condition['c.store_name'] = ['neq',''];
        // dump($condition);
        $sort_order = 'a.order_id desc';
        $count = M('order a')
            ->join('ty_users b ON a.user_id = b.user_id','LEFT')
            ->join('ty_store c ON a.store_id = c.store_id','LEFT')
            ->join('ty_users e ON a.driver_id = e.user_id','LEFT')
            ->where($condition)->count();
        $Page  = new AjaxPage($count,20);
        //  搜索条件下 分页赋值

        $show = $Page->show();
        //获取订单列表
        $orderList = $orderLogic->getOrderList($condition,$sort_order,$Page->firstRow,$Page->listRows);

        //获取主订单号
        foreach($orderList as $key=>$value){
            //去重复
            $goods = M('order_goods a')->field('a.*,b.original_img')
                ->join('ty_goods b ON a.goods_id = b.goods_id')
                ->where(array('a.order_id'=>$value['order_id']))
                ->select();
            $coupon = M('coupon')->where(['id'=>$value['coupon_id']])->getField('name');
            if(!empty($coupon)){
                $orderList[$key]['coupon_name'] = $coupon;
            }else{
                $orderList[$key]['coupon_name'] = '';
            }
            $tuihuo=M('return_goods')->where('status <> 3 and order_id='.$value['order_id'])->select();$tuihuos=$tuihuo0=0;
            foreach($tuihuo as $vs){
                $tuihuo0+=\sanwei(($vs['member_goods_price']+$vs['yijia'])*$vs['goods_num']);
                $tuihuos+=\sanwei($vs['member_goods_price']*$vs['goods_num']-$vs['member_goods_price']*$vs['goods_num']*$vs['points']/100);
            }

            if($orderList[$key]['fast_flag'] && $orderList[$key]['shop_fast_flag']){
                $orderList[$key]['fast_text'] = '快线订单';
            }else{
                $orderList[$key]['fast_text'] = '';
            }
            $orderList[$key]["ruku"]=M('order_jian')->where('order_id='.$value['order_id'].' and '.$this->z.'status_r=1')->count();
            $orderList[$key]["chuku"]=M('order_jian')->where('order_id='.$value['order_id'].' and '.$this->z.'status_c=1')->count();
            $orderList[$key]["tuihuo0"]=$tuihuo0;$orderList[$key]["tuihuo"]=$tuihuos;
            $orderList[$key]["order_price"]=order_price($value['order_id']);
            $orderList[$key]["suoshu_name"]=M('fenbu')->where('fenbu_id='.$value['fenbu_id'])->getField('fenbu_name');
            $orderList[$key]["usuoshu_name"]=M('fenbu')->where('fenbu_id='.$value['ufenbu_id'])->getField('fenbu_name');
            $orderList[$key]["order_amount"]=($value['order_amount']+$value['yijia_heji']);
            foreach($goods as $keys=>$vs){
                $goods[$keys]['tuihuo_num']=M('return_goods')->where('status <> 3 and  order_id='.$value['order_id'].' and spec_key="'.$vs['spec_key'].'"')->sum('goods_num');
                if(empty($goods[$keys]['tuihuo_num'])){
                    $goods[$keys]['tuihuo_num'] = 0;
                }
                //if(session('fenbu_id')!=0){
                $goods[$keys]['member_goods_price']=$vs['member_goods_price']+$vs['yijia'];

                $spec_img = M('spec_image')->where(['spec_image_id'=>$vs['spec_key']])->getField('src');
                if($spec_img){
                    $goods[$keys]['original_img'] = C('MYOSS')['url2'].$spec_img;
                }else{
                    $goods[$keys]['original_img'] =  C('MYOSS')['url2'].$vs['original_img'];
                }

                //}
            }
            $orderList[$key]["g_list"]=$goods;

            $orderList[$key]["pay_name"]=M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>$value['pay_code']))->getField('name');

        }

        // echo json_encode($orderList);
        // dump($orderList);
        $store_list = M('store')->getField('store_id,store_name');
        $this->assign('store_list',$store_list);
        $this->assign('fenbu_list',$this->fenbu_list);
        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }

/*
     *订单维修首页
     */
    public function fix_list(){

        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }

        $heji_ptprice=$heji_ptprices=$heji_price=0;
        // 搜索条件
        $condition = array();
        if($begin && $end){
            $condition['fix_time'] = array('between',"$begin,$end");
        }

        I('status')!="" ? $condition['status'] = I('status') : false;
        I('type')!="" ? $condition['type'] = I('type') : false;
        I('getorder')!="" ? $condition['getorder'] = I('getorder') : false;
        I('biaoshi_xian')!="" ? $condition['b.biaoshi_xian'] = I('biaoshi_xian') : false;
        I('order_sn') && $condition['_string'] = ' (remark like "%'.I('order_sn').'%")  OR (a.order_sn like "%'.I('order_sn').'%") ';


        I('consignee') && $condition['_string'] = ' (b.nickname like "%'.I('consignee').'%")  OR (b.company like "%'.I('consignee').'%") OR (d.store_name like "%'.I('consignee').'%") ';
        if(I('fenbu_id') != -1 && I('fenbu_id') != ''){
            I('fenbu_id')!=0 ? $condition['b.fenbu_id'] = I('fenbu_id') : $condition['b.fenbu_id'] = \session('fenbu_id');
            session('fenbu_id')==0 ? $condition['d.fenbu_id'] = session('fenbu_id') : false;
        }


        $count = M('fix_goods a')
            ->field('a.member_goods_price,a.goods_num,a.order_sn,CONCAT(b.biaoshi_xian,b.biaoshi,if(b.fast_flag="1","快","")) as company,d.tuihuo_status')
            ->join('ty_users b ON a.user_id = b.user_id','LEFT')
            ->join('ty_store d ON a.store_id = d.store_id','LEFT')
            ->group('a.id')
            ->where($condition)->count();


        $Page  = new Page($count,20);
        //  搜索条件下 分页赋值

        $show = $Page->show();
        //获取订单列表
        $orderList = M('fix_goods a')
            ->field('a.*,(a.member_goods_price),b.*,c.goods_name,d.store_name,CONCAT(b.biaoshi_xian,b.biaoshi,if(b.fast_flag="1","快","")) as bianshi_xian,e.key_name')
            ->join('ty_users b ON a.user_id = b.user_id','LEFT')
            ->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
            ->join('ty_store d ON a.store_id = d.store_id','LEFT')
            ->join('ty_spec_goods_price e ON a.spec_key = e.key','LEFT')
            ->where($condition)->limit("$Page->firstRow,$Page->listRows")->order('a.id desc')->select();
        foreach ($orderList as &$item){
            $item['fix_sn'] = M('order')->where(['fix_id'=>$item['id']])->getField('order_sn');
        }

        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('fenbu_list',$this->fenbu_list);
        $this->display();
    }
    
    
    /**
     *维修单
     */
    public function fix_edit_order(){
        $id = I('id');
        $order_sn = I('order_sn');
        $where=array();
        if($id){
            $where['id']=$id; //如果是修改。

            $orderGoods=M('fix_goods a')
                ->field('a.*,b.nickname,b.company,c.store_name,c.store_phone,d.goods_name')
                ->join('ty_users b on a.user_id=b.user_id','LEFT')
                ->join('ty_store c on a.store_id=c.store_id','LEFT')
                ->join('ty_goods d on a.goods_id=d.goods_id','LEFT')
                ->where($where)
                ->find();
            $spec=M('spec_goods_price')->where('`key`="'.$orderGoods['spec_key'].'"')->find();
            $orderGoods['guige']=$spec['key_name'];
        }

        if($order_sn){
            $orderGoods = M('order a')
                ->field('a.*,b.nickname,b.company,c.store_name,c.store_phone')
                ->join('ty_users b on a.user_id=b.user_id','LEFT')
                ->join('ty_store c on a.store_id=c.store_id','LEFT')
                ->where(['a.order_sn'=>$order_sn])->find();
        }


        if(IS_POST)
        {
            if($id){ //修改
                M('fix_goods')->where('id='.$id)->save([
                    'order_sn'=>I('order_sn'),
                    'goods_num'=>I('goods_num'),
                    'user_id'=>I('user_id'),
                    'store_id'=>I('store_id'),
                    'remark'=>I('remark'),
                    'reason'=>I('reason')
                ]);
                $this->success('修改成功','/index.php?m=admin&c=Order&a=fix_edit_order&id='.$id);
            }else{
                $goods_ids=I('goods_ids');
                $reasons=I('reasons');
                $prices=I('prices');
                $keys=I('keys');
                $goods_nums=I('goods_nums');
                // dump(I('store_id'));
                $tuihuo_status = M('store')->where(['store_id'=>I('store_id')])->getField('open_return');

                if($tuihuo_status != 1){
                    $this->error('店铺已经长关店');
                }
                
                if($goods_ids){
                    foreach($goods_ids as $key=>$v){
                        if(!$keys[$key]){
                            $this->success('请选择规格','/index.php/Admin/Order/fix_list');
                        }
                        M('fix_goods')->add([
                            'order_sn'=>I('order_sn'),
                            'order_id'=>I('order_id'),
                            'goods_id'=>$v,
                            'user_id'=>I('user_id'),
                            'store_id'=>I('store_id'),
                            'type'=>I('type'),
                            'goods_num'=>$goods_nums[$key],
                            'remark'=>I('remark'),
                            'fix_time'=>strtotime(I('tuihuo_time')),
                            'addtime'=>strtotime(date("Y-m-d H:i:s", time())),
                            'member_goods_price'=>$prices[$key],
                            'reason'=>$reasons[$key],
                            'spec_key'=>$keys[$key],
                            'admin_id'=>session('admin_id')
                        ]);
                    }
                }
                $this->success('添加成功','/index.php/Admin/Order/fix_list');
            }
            exit;
        }


        //echo \json_encode($orderGoods);exit;
        $this->assign('order',$orderGoods);
        $this->assign('order_sn',$order_sn);
        $this->display();
    }
    /*
    *导出维修单
    */
    public function export_fix(){

        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        // 搜索条件
        $condition = array();
        if($begin && $end){
            $condition['addtime'] = array('between',"$begin,$end");
        }

        I('status')!="" ? $condition['status'] = I('status') : false;
        I('biaoshi_xian')!="" ? $condition['b.biaoshi_xian'] = I('biaoshi_xian') : false;
        I('type')!="" ? $condition['type'] = I('type') : false;
        //I('order_sn') ? $condition['remark'] = array('like','%'.trim(I('order_sn')).'%') : false;
        I('order_sn') && $condition['_string'] = ' (remark like "%'.I('order_sn').'%")  OR (order_sn like "%'.I('order_sn').'%") ';
        I('consignee') && $condition['_string'] = ' (nickname like "%'.I('consignee').'%")  OR (company like "%'.I('consignee').'%") OR (store_name like "%'.I('consignee').'%") ';

        if(I('fenbu_id') != -1){
            I('fenbu_id')!=0 ? $condition['b.fenbu_id'] = I('fenbu_id') : $condition['b.fenbu_id'] = \session('fenbu_id');
            session('fenbu_id')==0 ? $condition['d.fenbu_id'] = session('fenbu_id') : false;
        }


        $strTable ='<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">单号/备注</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">商家</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">买家</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">单价</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">数量</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">创建时间</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">类型</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">完成时间</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">关联单号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">领取状态</td>';
        $strTable .= '</tr>';

        $orderList = M('fix_goods a')
            ->field('a.*,(a.member_goods_price),b.*,c.goods_name,d.store_name,CONCAT(b.biaoshi_xian,b.biaoshi,if(b.fast_flag="1","快","")) as bianshi_xian,e.key_name')
            ->join('ty_users b ON a.user_id = b.user_id','LEFT')
            ->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
            ->join('ty_store d ON a.store_id = d.store_id','LEFT')
            ->join('ty_spec_goods_price e ON a.spec_key = e.key','LEFT')
            ->where($condition)->order('a.id desc')->select();
        foreach ($orderList as &$item){
            $item['fix_sn'] = M('order')->where(['fix_id'=>$item['id']])->getField('order_sn');
            $item['receive'] = $item['is_receive'] ? '已领取' : '未领取';
            $item['status_str'] = $item['status'] ? '已完成' : '未完成';
            $item['type_str'] = $item['type'] ? '维修' : '换货';
            $item['status_time'] = $item['status_time']??'未完成';

            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$item['order_sn'].'/'.$item['remark'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$item['store_name'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$item['company'].'('.$item['bianshi_xian'].')</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$item['goods_name'].'【'.$item['key_name'].'】</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$item['member_goods_price'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$item['goods_num'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.\date('Y-m-d H:i:s',$item['addtime']).'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$item['type_str'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$item['status_str'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$item['status_time'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$item['fix_sn'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$item['receive'].' </td>';
            $strTable .= '</tr>';
        }

        $strTable .='</table>';

        unset($orderList);
        downloadExcel($strTable,'联鑫壹天达维修换货单');
        exit();

    }
       /**
     * 删除某个退换货申请
     */
    public function fix_del(){
        $id=I('id');
        $order_id=I('order_id');
        if(!empty($id) && !empty($order_id)){
            M('fix_goods')->where("id = $id and order_id=$order_id")->delete();
            exit(json_encode([
                'code'=>'200',
                'msg'=>'删除成功！'
            ]));
        }

    }
    /**
     * 一键批量入库
     * */
    public function plOneclickstorage(){

        $ids = I('ids');
        $list = M('order')->field('order_id')->where(['order_id'=>['in',$ids],'stock_up'=>2,'jian_count'=>['gt',0],'order_status'=>0])->select();


        $basic = tpCache('basic');
        $fast_ruku_time = $basic['fast_ruku_time'];
        $slow_ruku_time = $basic['slow_ruku_time'];
        $now = time();
        $ruku_time = strtotime(date("Y-m-d H:i:s"));
        foreach ($list as $k=>$v){
            if($fast_ruku_time && $slow_ruku_time) {
                $fast_time = explode('-', $fast_ruku_time);
                $slow_time = explode('-', $slow_ruku_time);
                $fast_start_time = strtotime($fast_time[0]);
                $fast_end_time = strtotime($fast_time[1]);
                $slow_start_time = strtotime($slow_time[0]);
                $slow_end_time = strtotime($slow_time[1]);
                $fast_flag = M('order a')
                    ->join('ty_users b ON a.user_id = b.user_id', 'LEFT')
                    ->where(['a.order_id' => $v['order_id']])->getField('b.fast_flag');
                if ($fast_flag) {
                    if (($now > $fast_start_time) && ($now < $fast_end_time)) {
                        $data = array('code' => 0, 'msg' => '快线订单禁止入库', 'data' =>[]);
                        $this->ajaxReturn($data);
                        die;
                        // exit(json_encode(array("status"=>0,'msg'=>'快线订单禁止入库!')));
                    }
                } else {
                    if (($now > $slow_start_time) && ($now < $slow_end_time)) {
                        $data = array('code' => 0, 'msg' => '订单禁止入库', 'data' =>[]);
                        $this->ajaxReturn($data);
                        die;
                    }
                }
            }
            M('order_jian')
                ->where(['order_id'=>$v['order_id']])
                ->save(['status_r'=>1,'ruku_time'=>$ruku_time,'pda_name_ruku'=>'ycp-88']);
            M('order')->where('order_id='.$v['order_id'])
                ->save([
                    'order_status'=>1,
                    'shipping_status'=>1,
                    'ruku_last_time'=>$ruku_time
                ]);
        }
        $data = array('code' => 1, 'msg' => '入库成功', 'data' =>[]);
        $this->ajaxReturn($data);

    }


    public function look_biaoqian(){ //查看标签
        $order=M('order')->where('order_id='.I('order_id'))->find();
        if($order){
            $pic_data=[];
            if($order['jian_count'] <=150){
                for($i=1;$i<=(int)$order['jian_count'];$i++){
                    $erwei=$this->mypng(I('order_id'),$i,1); //0条码，1二维码
                    $pic_data[]=[
                        'alt'=>$order['consignee'],
                        'pid'=>$i,
                        'src'=>$erwei,
                        'thumb'=>''
                    ];
                }
            }

            echo \json_encode([
                "status"=>2,
                "msg"=>"",
                "title"=>$order['consignee'],
                "id"=>8,
                "start"=> 0,
                "data"=>$pic_data
            ]);
        }
    }


    public function look_qrcode(){ //查看取货码

        $return_order_sn = I('order_sn');
        if(empty($return_order_sn))
            $this->error('非法操作！');

        // 搜索条件
        $orderLogic = new OrderLogic();

        $orders = M('return_goods a')
            ->field('a.*,b.mobile,b.company,b.biaoshi,b.biaoshi_xian,b.fast_flag,b.company_address,c.store_name,c.store_phone,(member_goods_price+yijia) as member_goods_price,b.fast_flag ,c.fast_flag as store_fast_flag')
            ->join('ty_users b on a.user_id=b.user_id')
            ->join('ty_store c on a.store_id=c.store_id')
            ->where("a.return_order_sn in (".$return_order_sn.") and a.status <> 3")->order('a.id desc')->select();

        $orders = group_same_key($orders,'return_order_sn');
        $orders = array_values($orders);

        foreach($orders as $key=>$vv){
            $return_ids = array_column($vv,'id');
        }

        $erwei = tuihuoQRcode(['id'=>join(',',$return_ids)],'self',2);
        $pic_data[]=[
            'alt'=>'',
            'pid'=>0,
            'src'=>$erwei,
            'thumb'=>''
        ];

        echo \json_encode([
            "status"=>2,
            "msg"=>"",
            "title"=>$order['consignee'],
            "id"=>8,
            "start"=> 0,
            "data"=>$pic_data
        ]);
    }


    public function mypng($order_id,$jian,$type=1){
        $mydata = \json_encode([
            (int)$order_id,$jian
        ]);
        $picname=\md5($mydata);

        if($type==1){
            $filename = '/Public/goodsqrcode/erwei/'.$picname.'.png';
            Vendor('phpqrcode.phpqrcode');
            $object = new \QRcode();
            $level = 'Q'; //容错级别 分为L、M、Q、H
            $size = 6; //点的大小 1~10,手机端用4即可
            if (!file_exists($filename)) {
                $object->png($mydata,'.'.$filename,$level,$size);
            }
        }else{
            $filename = './Public/goodsqrcode/erwei/'.$picname.'.png';
            $font = new BCGFontFile('./ThinkPHP/Library/Vendor/yiwei/font/Arial.ttf', 18);
            $color_black = new BCGColor(0, 0, 0);
            $color_white = new BCGColor(255, 255, 255);
            $drawException = null;
            try {
                $code = new BCGcode128();
                $code->setScale(2); // Resolution
                $code->setThickness(30); // Thickness
                $code->setForegroundColor($color_black); // Color of bars
                $code->setBackgroundColor($color_white); // Color of spaces
                $code->setFont(0); // Font (or 0)
                $code->setStart(null);
                $code->setTilde(true);
                $code->parse($mydata); // Text
            } catch (Exception $exception) {
                $drawException = $exception;
            }
            if (!file_exists($filename)) {
                $drawing = new BCGDrawing('', $color_white);
                $drawing->setBarcode($code);
                $drawing->setFilename($filename);
                $drawing->draw();
                $drawing->finish(BCGDrawing::IMG_FORMAT_PNG);
            }
        }
        $picurl=SITE_URL.$filename;
        return $picurl;
    }
    /*
     *司机待配送订单首页
     */
    public function index_sj(){
        $begin = date('Y-m-d 00:00',(time()-30*60*60*24));//30天前
        $end = date('Y-m-d 23:59',strtotime('+1 days'));
        $this->assign('fenbu_list',$this->fenbu_list);
        $this->assign('timegap',$begin.' - '.$end);
        $this->display();
    }
	
	
	// public function aa(){ 
	// 	$condition['_string'] = 'c.biaoshi_xian="65号线" ';
	// 	$condition['b.pda_name_chuku'] = 'tlc-88';
	// 	$condition['order_status'] = 1;//判断要列出的订单状态
	// 	$condition['shipping_status'] = 1;
	// 	// $condition['a.chuku_last_time'] = ['>',1699545600];
	// 	// $condition['a.chuku_last_time'] = ['<',1699632000];
	// 	$condition['a.chuku_last_time'] = array('between',"1699545600,1699632000");
		
	// 	$count = M('order a')
	// 	    ->field('a.order_id,c.biaoshi_xian')
	// 	    ->join('ty_order_jian b on a.order_id=b.order_id','LEFT')
	// 	    ->join('ty_users c on a.user_id=c.user_id','LEFT')
	// 	    ->where($condition)
	// 		->order('a.order_id desc')
	// 		->group('a.order_id')->select();
			
	// 	foreach($count as $v){
	// 		M('order')->where(['order_id'=>$v['order_id']])->save(['chuku_count'=>0,'driver_id'=>0,'pda_qdzt'=>0]);
	// 		M('order_jian')->where(['order_id'=>$v['order_id']])->save(['pda_name_chuku'=>null,'status_c'=>0,'chuku_time'=>null]);
	// 	}
		
	// 	print_r($count);exit;
	// }
	
    /*
     *司机待配送Ajax首页
     */
    public function ajaxindex_sj(){
        $timegap = I('timegap');
        if($timegap){
             $this->assign('timegap',$timegap);
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
            
        }
        // 搜索条件
        $condition = array();
        I('consignee') ? $condition['c.company'] = array('like','%'.trim(I('consignee')).'%') : false;
        // if($begin && $end){
        // 	$condition['add_time'] = array('between',"$begin,$end");
        // }
        $store_name = I('store_name'); $store_ids='';
        I('fast_flag') !== '' ? $condition['c.fast_flag'] = I('fast_flag') : false;
        I('biaoshi_xian') ? $condition['c.biaoshi_xian'] = I('biaoshi_xian') : false;

        if($store_name)
        {
            $store_id_arr = M('store')->where("store_name like '%$store_name%'")->getField('store_id');
            if($store_id_arr)
            {
                $store_ids="a.store_id=".$store_id_arr;

            }
        }
        if(!empty(session('fenbu_id')) && I('fenbu_id') ){
            $condition['a.ufenbu_id']=session('fenbu_id');
        }
        if(session('fenbu_id') !== '0'){
            // $where .= " and fenbu_id = ".session('fenbu_id');
            $condition['a.ufenbu_id']=session('fenbu_id');
        }else{
            
            if(I('fenbu_id') === '0'){
                // $where .= " and fenbu_id = ".I('fenbu_id');
                $condition['a.ufenbu_id']=0;
            }
            if(!empty(I('fenbu_id'))){
                
                // $where .= " and fenbu_id = ".I('fenbu_id');
                $condition['a.ufenbu_id']=I('fenbu_id');
            }
        }
        $condition['a.pda_qdzt'] = ['in','0,2'];
        $condition['b.status_r'] = 1;
        $condition['b.status_c'] = 0;
        $condition['b.ruku_time'] = array('between',"$begin,$end");
        $this->z='';

        I('order_sn') ? $condition['order_sn'] =  array('like','%'.trim(I('order_sn')).'%') : false;
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;
        // I('biaoshi') && $condition['_string'] = ' (c.biaoshi like "%'.I('biaoshi').'%")  OR (c.biaoshi_xian like "'.I('biaoshi').'%") ';

        //$condition['is_pint'] = 0;
        $condition['order_status'] = 1;//判断要列出的订单状态
        $condition['shipping_status'] = 1;
        $condition['a.jian_count'] = ['gt',0];
        $condition['a.ruku_count'] = ['exp',' = a.jian_count'];
        $condition['a.chuku_count'] = ['exp',' <> a.ruku_count'];
        // dump($condition);
        $count = M('order a')
            ->field('a.order_id')
            ->join('ty_order_jian b on a.order_id=b.order_id','LEFT')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->where($condition)->order('c.xsort asc')->group('a.user_id')->select();

        $Page= new AjaxPage2(count($count));
        //  搜索条件下 分页赋值
        $start=$Page->firstRow;
        $page_size=$Page->listRows;
        $show = $Page->show();

        $orderList =  M('order a')
            ->field('a.user_id,c.company,a.fenbu_id,a.ufenbu_id,b.'.$this->z.'ruku_time')
            ->join('ty_order_jian b on a.order_id=b.order_id','LEFT')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->where($condition)->limit("$start,$page_size")->order('c.xsort asc') //->fetchSql()
            ->group('a.user_id')->select(); //过滤获取主订单

//\print_r($orderList);
        foreach($orderList as $key=>$value){ //整理子单
            $condition['a.user_id'] = $value['user_id'];
            $order_list=M('order a')->field('a.*,c.biaoshi,c.biaoshi_xian,a.same_order')
                ->join('ty_order_jian b on a.order_id=b.order_id','INNER')
                ->join('ty_users c on a.user_id=c.user_id','LEFT')
                ->where($condition)->group('a.order_id')
                ->group('b.order_id')
                ->order('c.xsort asc')
                ->select();
            $zong=M('order a')
                ->field('sum(a.jian_count) as jian_count,sum(a.ruku_count) as ruku_count')
                ->join('ty_users c on a.user_id=c.user_id','LEFT')
                ->where('a.user_id ='.$value['user_id'].' and a.jian_count >0 and a.ruku_count >a.chuku_count')
                ->order('c.xsort asc')
                ->group('a.order_id')
                ->select();
                // dump($zong);
            $orderList[$key]["zjian_count"]=$zong[0]['jian_count'];
            $orderList[$key]["zruku_count"]=$zong[0]['ruku_count'];
            $orderList[$key]["consignee"]=$order_list[0]['consignee'];
            $orderList[$key]["mobile"]=$order_list[0]['mobile'];
            $orderList[$key]["address"]=$order_list[0]['address'];
            $orderList[$key]["biaoshi"]=$order_list[0]['biaoshi'];
            $orderList[$key]["biaoshi_xian"]=$order_list[0]['biaoshi_xian'];
            $orderList[$key]["dayin_num"]=$order_list[0]['dayin_num'];
            $orderList[$key]["order_list"]=$order_list;
            $orderList[$key]["shijian"]=\date('Y-m-d',$value[$this->z.'ruku_time']);
            $orderList[$key]["suoshu_name"]=M('fenbu')->where('fenbu_id='.$value['fenbu_id'])->getField('fenbu_name');
            $order_ids = [];
            foreach($order_list as $keys=>$values){ //整理子单产品
                $order_ids[] = $values['order_id'];
                $orderList[$key]["order_list"][$keys]["ruku"]=M('order_jian')->where('order_id='.$values['order_id'].' and '.$this->z.'status_r=1')->count();
                $orderList[$key]["order_list"][$keys]["chuku"]=M('order_jian')->where('order_id='.$values['order_id'].' and '.$this->z.'status_c=1')->count();
                
                $zong_jian = M('order')->where(['same_order'=>$values['same_order'],'order_status'=>1,'chuku_count'=>['eq',0]])->sum('jian_count');
                $ru_jian = M('order')->where(['same_order'=>$values['same_order'],'order_status'=>1,'chuku_count'=>['eq',0]])->sum('ruku_count');
                $orderList[$key]["order_list"][$keys]['zong_jian'] =  $zong_jian;
                $orderList[$key]["order_list"][$keys]['ru_jian'] =  $ru_jian;

                $orderGoods = M('order_goods a')->field('a.*,b.original_img')->join('ty_goods b ON a.goods_id = b.goods_id')->where(array('a.order_id'=>$values['order_id']))->select();
                foreach ($orderGoods as $k=>$vs){
                    $orderGoods[$k]['original_img'] = C('MYOSS')['url2'].$vs['original_img'];
                }
                $orderList[$key]["order_list"][$keys]["g_list"]=$orderGoods;


            }
            $orderList[$key]['order_ids'] = implode(',',$order_ids);
            

        }

        //echo \json_encode($orderList);exit;

        $store_list = M('store')->getField('store_id,store_name');
        $this->assign('store_list',$store_list);
        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }

    /*
     *司机已配送订单首页
     */
    public function index_sj_log(){
        $begin = date('Y-m-d H:i',(time()-1*60*60*6));//2天前
        $end = date('Y-m-d 23:59',strtotime('+1 days'));
        $this->assign('timegap',$begin.' - '.$end);
        $this->assign('fenbu_list',$this->fenbu_list);
        $this->display();
    }
    /*
     *司机已配送Ajax记录
     */
    public function ajaxindex_sj_log(){
        $timegap = I('timegap');
        $driver=I('driver');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        // 搜索条件
        $condition = array();
        I('consignee') ? $condition['c.company'] = array('like','%'.trim(I('consignee')).'%') : false;


        $store_name = I('store_name'); $store_ids='';
        if($store_name)
        {
            $store_id_arr = M('store')->where("store_name like '%$store_name%'")->getField('store_id');
            if($store_id_arr)
            {
                $store_ids="a.store_id=".$store_id_arr;
            }
        }
  if(!empty(session('fenbu_id'))){
            $condition['a.ufenbu_id']=session('fenbu_id');
        }
//        I('order_sn') ? $condition['order_sn'] =  trim(I('order_sn')) : false;
//        I('order_sn') ? $condition['order_sn'] =  array('like','%'.trim(I('order_sn')).'%') : false;
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;
        I('biaoshi_xian') && $condition['_string'] = ' c.biaoshi_xian like "'.I('biaoshi_xian').'%" ';

        if(I('order_sn') ){
            $subQuery_orderIds = M()->query('select order_id from ty_order WHERE LOCATE('.I('order_sn').',order_sn) > 0');
            foreach ($subQuery_orderIds as $item){
                $ids[] = $item['order_id'];
            }
            if($ids){
                $condition['a.order_id'] = ['in',join(',',$ids)];
            }else{
                $condition['a.order_id'] = 0;
            }

        }

        if($driver){
            $condition['d.nick_name'] = $driver;
        }

//		$condition['order_status'] = 1;//判断要列出的订单状态
        $condition['shipping_status'] = 1;
        $condition['pda_qdzt'] = 0;

        $condition['a.chuku_last_time'] = array('between',"$begin,$end");
        $this->z='';


        $condition['a.chuku_count'] = ['exp','= a.jian_count'];
        $condition['a.ruku_count'] = ['exp','= a.jian_count'];

        // dump($condition);
        $heji = 0;
        $count = M('order a')
            ->field('a.order_sn,a.consignee,a.user_id,a.add_time,a.order_id,(a.order_amount+a.yijia_heji) as order_amount')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->join('ty_users d on a.driver_id=d.user_id','LEFT')
            ->where($condition)
            ->order('c.xsort asc')->select();
        foreach ($count as $value){
            $heji+= $value['order_amount'];
        }

//        dump($count);
        $Page= new AjaxPage2(count($count),20);
        //  搜索条件下 分页赋值
        $start=$Page->firstRow;
        $page_size=$Page->listRows;
        $show = $Page->show();


        $orderList =  M('order a')
            ->field('a.*,c.*,d.nick_name')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->join('ty_users d on a.driver_id=d.user_id','LEFT')
            ->where($condition)->limit("$start,$page_size")->order('c.xsort asc')
            ->select(); //过滤获取主订单

        foreach($orderList as $keys=>$values){ //整理子单产品
            $orderGoods = M('order_goods a')->field('a.*,b.original_img')->join('ty_goods b ON a.goods_id = b.goods_id')->where(array('a.order_id'=>$values['order_id']))->select();
            foreach ($orderGoods as $k=>$vs){
                $orderGoods[$k]['original_img'] =  C('MYOSS')['url2'].$vs['original_img'];
            }
            $orderList[$keys]["g_list"]=$orderGoods;
            $orderList[$keys]["ruku"]=$values['ruku_count'];
            $orderList[$keys]["chuku"]=$values['chuku_count'];
            $orderList[$keys]["shijian"]=\date('Y-m-d H:i',$values['chuku_last_time']);
        }
        $store_list = M('store')->getField('store_id,store_name');
        $this->assign('store_list',$store_list);
        $this->assign('orderList',$orderList);
        $this->assign('z',$this->z);
        $this->assign('siji_heji',$heji);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }

    public function export_order_duizhang()
    {
        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        // 搜索条件
        $condition = array();
        I('consignee') ? $condition['consignee'] = array('like','%'.trim(I('consignee')).'%') : false;

        $store_name = I('store_name'); $store_ids='';
        if($store_name)
        {
            $store_id_arr = M('store')->where("store_name like '%$store_name%'")->getField('store_id');
            if($store_id_arr)
            {
                $store_ids="a.store_id=".$store_id_arr;
            }
        }

        I('order_sn') ? $condition2['order_sn'] =  array('like','%'.trim(I('order_sn')).'%') : false;
        I('shipping_status') != '' ? $condition2['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;
        I('biaoshi') && $condition['_string'] = ' (c.biaoshi like "%'.I('biaoshi').'%")  OR (c.biaoshi_xian="'.I('biaoshi').'") ';
        I('biaoshi_xian') ? $condition['c.biaoshi_xian'] = I('biaoshi_xian') : false;
        $condition2['order_status'] = 1;//判断要列出的订单状态
        $condition2['shipping_status'] = 1;
        $condition2['pda_qdzt'] = ['in','0,2'];
        
        $condition['order_status'] = 1;//判断要列出的订单状态
        $condition['shipping_status'] = 1;
        $condition['a.jian_count'] = ['gt',0];
        $condition['a.ruku_count'] = ['exp',' = a.jian_count'];
        $condition['a.chuku_count'] = ['exp',' <> a.ruku_count'];
        // $condition['b.'.$this->z.'status_r'] = 1;
        // $condition['b.'.$this->z.'status_c'] = 0;

        if(!empty(session('fenbu_id'))){ //分部
            $condition2['a.ufenbu_id']=session('fenbu_id');
            $condition2['b.zstatus_r'] = 1;
            $condition2['b.zstatus_c'] = 0;
            $condition2['b.zruku_time'] = array('between',"$begin,$end");
            $this->z='z';
        }elseif(empty(session('fenbu_id')) && !empty(I('fenbu_id'))){ //总部筛选
            $condition2['a.ufenbu_id']=I('fenbu_id');
            $condition2['b.zstatus_r'] = 1;
            $condition2['b.zstatus_c'] = 0;
            $condition2['b.zruku_time'] = array('between',"$begin,$end");
            $this->z='z';
        }else{	//总部默认
            $condition2['b.status_r'] = 1;
            $condition2['b.status_c'] = 0;
            $condition2['b.ruku_time'] = array('between',"$begin,$end");
            $this->z='';
        }

        //echo \json_encode($condition);exit;
        $orderList =  M('order a')
            ->field('a.user_id,a.yijia_heji,b.'.$this->z.'ruku_time,c.biaoshi,c.biaoshi_xian,c.nickname,c.company')
            ->join('ty_order_jian b on a.order_id=b.order_id','LEFT')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->where($condition)->where($condition2)->order('c.xsort asc')
            ->group('a.user_id')->select(); //过滤获取主订单


        $zongji=$i=0;
        foreach($orderList as $key=>$value){ //整理子单

            $order_list =  M('order a')
                ->field('a.order_id,a.order_sn,a.jian_count,a.order_amount,a.yijia_heji,b.'.$this->z.'ruku_time,c.biaoshi,c.biaoshi_xian,c.nick_name,c.company,d.store_name')
                ->join('ty_order_jian b on a.order_id=b.order_id','LEFT')
                ->join('ty_users c on a.user_id=c.user_id','LEFT')
                ->join('ty_store d on a.store_id=d.store_id','LEFT')
                ->where('a.user_id='.$value['user_id'])->where($condition2)->group('a.order_id')
                //->group('b.order_id')
                ->order('c.xsort asc')
                ->select(); //过滤获取主订单

            $heji_price=0;
            foreach($order_list as $keys=>$values){ //整理子单产品
                $heji_price+=$values['order_amount'];
                $zongji+=$values['order_amount']+$values['yijia_heji'];
            }

            $orderList[$key]["order_amount"]=$heji_price;
            $orderList[$key]["order_list"]=$order_list;
        }


        $strTable ='<table style="width:210mm;table-layout:fixed" border="1">';
        $strTable .= '<tr style="font-weight:bold">';
        $strTable .= '<td colspan="3" style="height:35px;">日期：&nbsp;&nbsp;&nbsp;年&nbsp;&nbsp;&nbsp;月&nbsp;&nbsp;&nbsp;日</td>';
        $strTable .= '<td colspan="3">姓名：  </td>';
        $strTable .= '<td colspan="2">车牌：  </td>';
        $strTable .= '<td colspan="3">线路：  </td>';
        $strTable .= '</tr>';
        $strTable .= '<tr style="font-weight:bold">';
        $strTable .= '<td style="height:35px;text-align:center">&nbsp;配送总金额&nbsp;</td>';
        $strTable .= '<td style="width:40px;text-align:center;word-break:break-all;">二维码</td>';
        $strTable .= '<td colspan="4" style="text-align:center">现金</td>';
        $strTable .= '<td colspan="2" style="text-align:center">退货金额</td>';
        $strTable .= '<td colspan="3" style="text-align:center">未配送金额</td>';
        //$strTable .= '<td colspan="2">&nbsp;&nbsp;</td>';
        $strTable .= '</tr>';
        $strTable .= '<tr>';
        $strTable .= '<td style="height:35px"></td>';
        $strTable .= '<td></td>';
        $strTable .= '<td colspan="4"></td>';
        $strTable .= '<td colspan="2"></td>';
        $strTable .= '<td colspan="3"></td>';
        //$strTable .= '<td colspan="2"></td>';
        $strTable .= '</tr>';
        $strTable .= '<tr style="font-weight:bold">';
        $strTable .= '<td style="text-align:center;font-size:12px;width:95px;height:35px;">序号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:40px;">客户名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:72px;">订单号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:52px;">件数</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:105px;">商家名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:38px;">线路</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:65px;">小计金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:65px;">合计金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:50px;">退货金额</td>';
        // $strTable .= '<td style="text-align:center;font-size:12px;width:50px;">POS机</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:50px;">&nbsp;二维码</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:60px;">&nbsp;现金&nbsp;</td>';
        $strTable .= '</tr>';

        foreach($orderList as $vs){
            $strTables='';$i++;$tuihuo=0;
            foreach($vs['order_list'] as $vss){
                // $tuilist=M('return_goods')->where('order_id='.$vss['order_id'])->select();
                // foreach($tuilist as $tv){
                // 	$tuihuo+=\sanwei($tv['member_goods_price']*$tv['goods_num']);
                // }
                $strTables .= '<tr>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px">'.substr($vss['order_sn'],-7).'</td>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px">'.$vss['jian_count'].'</td>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px">'.$vss['store_name'].'</td>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px">'.$vss['biaoshi_xian'].'</td>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px;color:red">'.($vss['order_amount']+$vss['yijia_heji']).'</td>';
                $strTables .= '</tr>';
            }


            $strTable .= '<tr style="border:1px solid #000">
		<td style="text-align:center;font-size:12px;border:1px;width:50px;">'.$i.'</td>
		<td style="text-align:center;font-size:12px;border:1px;width:40px;WORD-WRAP:break-all;">'.$vs['company'].'</td>
		<td colspan="5">
		<table width="500" border="1">
		'.$strTables.'
		</table>
		</td>
		<td style="text-align:center;font-size:12px;color:red;font-weight:bold">'.($vs['order_amount']+$vss['yijia_heji']).'</td>
		<td style="text-align:center;font-size:12px;color:red;font-weight:bold;color:green"></td>
		<td style="text-align:center;font-size:12px;color:red;font-weight:bold"></td>
		<td style="text-align:center;font-size:12px;color:red;font-weight:bold"></td>
		</tr>';
        }

        $strTable .= '<tr style="border:1px solid #000">
		<td colspan="6" style="text-align:right;font-weight:bold;height:32px">
		合计：
		</td>
		<td style="text-align:center;font-size:12px;color:red;font-weight:bold">'.$zongji.'</td>
		</tr>';
        $strTable .='</table>';
        unset($orderList);
        downloadExcel($strTable,'order');
        exit();
    }

    public function export_order_log()
    {
        $duizhang_sn = date('YmdHis');//生成对账总单号
        $driver=I('driver');
        $timegap = I('timegap');

        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        // 搜索条件
        $condition = array();
        I('consignee') ? $condition['consignee'] = array('like','%'.trim(I('consignee')).'%') : false;

        $store_name = I('store_name'); $store_ids='';
        if($store_name)
        {
            $store_id_arr = M('store')->where("store_name like '%$store_name%'")->getField('store_id');
            if($store_id_arr)
            {
                $store_ids="a.store_id=".$store_id_arr;
            }
        }

        I('order_sn') ? $condition['order_sn'] =  array('like','%'.trim(I('order_sn')).'%') : false;
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;
        I('biaoshi') && $condition['_string'] = ' (c.biaoshi like "%'.I('biaoshi').'%")  OR (c.biaoshi_xian="'.I('biaoshi').'") ';

        if($driver){
            $condition['d.nick_name'] = $driver;
        }else{
            $this->error('请填写司机名称，再导出');
        }

        $condition['order_status'] = 1;//判断要列出的订单状态
        $condition['shipping_status'] = 1;
        $condition['pda_qdzt'] = 0;
        // $condition['b.'.$this->z.'status_r'] = 1;
        // $condition['b.'.$this->z.'status_c'] = 0;


        $condition['a.chuku_last_time'] = array('between',"$begin,$end");

        $condition['a.chuku_count'] = ['exp','= a.jian_count'];
        $condition['a.ruku_count'] = ['exp','= a.jian_count'];
        
        //echo \json_encode($condition);exit;

        //        $orderList =  M('order a')
        //            ->field('a.order_id,a.user_id,c.biaoshi,c.biaoshi_xian,c.nickname,c.company,d.nick_name,a.driver_id,a.master_order_sn')
        //            ->join('ty_users c on a.user_id=c.user_id','LEFT')
        //            ->join('ty_users d on a.driver_id=d.user_id','LEFT')
        //            ->where($condition)->order('c.xsort asc')
        //            ->select(); //过滤获取主订单
        //
        //
        //        foreach ($orderList as $item){
        //            if(!$item['master_order_sn']){ //如果没有合并单号的默认给他一个
        //                $master_order_sn = get_order_sn(); //合并单号
        //                M('order')->where(['order_id'=>$item['order_id']])->save(['master_order_sn'=>$master_order_sn]); //修改合并单号
        //            }
        //        }


        $orderList =  M('order a')
            ->field('a.user_id,c.biaoshi,c.biaoshi_xian,c.nickname,c.company,d.nick_name,a.driver_id,a.master_order_sn')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->join('ty_users d on a.driver_id=d.user_id','LEFT')
            ->where($condition)->order('c.xsort asc')
            ->group('a.user_id')->select(); //过滤获取主订单

        //echo \json_encode($orderList);exit;
        $zongji=$totalzongjia=$coupontotal=$i=0;
        $orderIds = [];
        $driver_id = 0;
        $start_time = '';
        $end_time = '';

        foreach($orderList as $key=>$value) { //整理子单
            $driver_print_status = 1;
            $driver_order_id = [];

            $order_lists =  M('order a')
                ->field('a.ufenbu_id,a.order_id,a.order_sn,a.jian_count,a.coupon_price,(a.total_amount + a.yijia_heji) as total_amount,
                (a.order_amount + a.yijia_heji) as order_amount,c.biaoshi,c.biaoshi_xian,c.nickname,c.company,d.store_name,
                c.fast_flag,d.fast_flag as store_fast_flag,a.master_order_sn,a.driver_print,a.chuku_last_time')
                ->join('ty_users c on a.user_id=c.user_id')
                ->join('ty_store d on a.store_id=d.store_id')
                ->where('a.user_id='.$value['user_id'].' and  a.ruku_count =  a.jian_count and a.chuku_count = a.jian_count and a.jian_count > 0 and a.chuku_last_time > '.$begin.' and a.chuku_last_time < '.$end.' and a.driver_id = '.$value['driver_id'])
                //->group('b.order_id')
                ->order('a.order_id desc')
                ->select(); //过滤获取主订单


            foreach($order_lists as $values){ //整理子单产品

                if(!$values['driver_print']){
                    $driver_print_status = 0;
                }
                $chuku_time = $values['chuku_last_time'];
                $diffTime = calculateHourDiff(time(),$chuku_time);


                if($diffTime < 5 || $values['ufenbu_id'] != 0){
                    $driver_order_id[] = $values['order_id'];
                }
            }

            $master_order_sn = get_order_sn(); //合并单号
            if(!$driver_print_status && $driver_order_id){
                M('order')->where(['order_id'=>['in',join(',',$driver_order_id)]])->save(['master_order_sn'=>$master_order_sn,'driver_print'=>1]); //修改合并单号
            }

        }




        foreach($orderList as $key=>$value){ //整理子单

            $order_list =  M('order a')
                ->field('a.add_time,a.ufenbu_id,a.store_id,a.order_id,a.order_sn,a.jian_count,a.coupon_price,
                (a.total_amount + a.yijia_heji) as total_amount,(a.order_amount + a.yijia_heji) as order_amount,c.biaoshi,c.biaoshi_xian,
                c.nickname,c.company,d.store_name,c.fast_flag,d.fast_flag as store_fast_flag,a.master_order_sn,a.driver_print,
                a.chuku_last_time,c.mobile,c.company_address')
                ->join('ty_users c on a.user_id=c.user_id')
                ->join('ty_store d on a.store_id=d.store_id')
                ->where('a.user_id='.$value['user_id'].' and  a.ruku_count =  a.jian_count and a.chuku_count = a.jian_count and a.jian_count > 0 and a.chuku_last_time > '.$begin.' and a.chuku_last_time < '.$end.' and a.driver_id = '.$value['driver_id'])
                //->group('b.order_id')
                ->order('a.master_order_sn asc')
                ->select(); //过滤获取主订单
//            dump($order_list);
            $heji_price=0;
            $uniqueStores = [];
            foreach($order_list as $keys=>$values){ //整理子单产品
                //M('order')->where(['order_id'=>$values['order_id']])->save(['duizhang_sn'=>$duizhang_sn]);
                $orderIds[] = $values['order_id'];
                $heji_price+=$values['order_amount'];
                $zongji+=$values['order_amount'];
                $totalzongjia+=$values['total_amount'];
                $coupontotal+=$values['coupon_price'];
                $storeId = $values['store_id'];
                if (!in_array($values['store_id'],$uniqueStores)) {
//                    $uniqueStores[] = $values['store_id'];
                    array_push($uniqueStores, $values['store_id']);
                }
            }
            $orderList[$key]['gift'] = '';
            if(!empty($uniqueStores)){
                foreach ($uniqueStores as $storeId){
                    $storeName = M('store')->where(['store_id'=>$storeId])->getField('store_name');

                    // 获取店铺活动
                    $activity = M('goods_full')->where([
                        'store_id' => $storeId,
                        'type' => 1,
                        'start_time' => ['elt', time()],
                        'end_time' => ['egt', time()]
                    ])->order('id desc')->find();

                    if ($activity) {
                        //查看是否是品牌满减
                        $where = [];
                        if(!empty($activity['brand_id'])){
                            $brand_id = implode(',',json_decode($activity['brand_id'],true));
                            $where['gs.store_cat_id1'] = ['in',$brand_id];
                        }
                        if(!empty($activity['goods_id'])){
                            $goods_id = implode(',',json_decode($activity['goods_id'],true));
                            $where['gs.goods_id'] = ['in',$goods_id];
                        }
                        
                        // 获取当天用户下单总金额
                        // $todayStart = strtotime(date('Y-m-d 00:00:00'));
                        // $todayEnd = strtotime(date('Y-m-d 23:59:59'));
                        $todayStart = strtotime(date('Y-m-d 00:00:00',$values['add_time']));
                        $todayEnd = strtotime(date('Y-m-d 23:59:59',$values['add_time']));
                        // $totalAmount = M('order')->where([
                        //     'user_id' => $value['user_id'],
                        //     'add_time' => ['between', [$todayStart, $todayEnd]],
                        // ])->sum('total_amount');
                        
                        $where['o.user_id'] = $value['user_id'];
                        $where['o.order_status'] = ['in','0,1,2'];
                        $where['o.store_id'] = $storeId;
                        $where['g.full_status'] = 0;
                        $where['o.add_time'] = ['between', [$todayStart, $todayEnd]];
                        
                        $totalAmount = M('order_goods g')
                	    ->join('ty_order o on o.order_id = g.order_id','left')
                	    ->join('ty_goods gs on gs.goods_id = g.goods_id','left')
                	    ->where($where)
                	    ->sum('(g.member_goods_price+g.yijia)*goods_num');
                        
                        if(empty($totalAmount)){
                            $totalAmount = 0;
                        }
                        // 判断是否达到活动条件
                        $finalGift = null;
                        $gifts = json_decode($activity['full_gift'], true);
                        usort($gifts, function($a, $b) {
                            return $b['price'] <=> $a['price'];
                        });
                        foreach ($gifts as $gift) {
                            if ($totalAmount >= $gift['price']) {
                                $finalGift = $gift['gift'];
                                break;
                            }
                        }
                        if($finalGift){
                            $orderList[$key]['gift'] .= $storeName.'店铺的赠品：'.$finalGift.',';
                        }
                    }
                }
            }



            $driver_id = $value['driver_id'];
            $start_time = date('Y-m-d H:i:s',$begin);
            $end_time = date('Y-m-d H:i:s',$end);
            $orderList[$key]["order_amount"]=$heji_price;
            $orderList[$key]["order_list"]=$order_list;
        }
        
        M('pda_duizhang')->add(['duizhang_sn'=>$duizhang_sn,'order_ids'=>json_encode($orderIds),'driver_id'=>$driver_id,'start_time'=>$start_time,'end_time'=>$end_time]); //记录总单号

        $strTable ='<table style="width:10mm;" border="1">';
        $strTable .= '<tr style="font-weight:bold">';
        $strTable .= '<td colspan="15" style="width:20px;height:35px;text-align: center;font-size:24px; font-weight: bold">联鑫壹天达五金商城配送总清单（新）</td>';
        $strTable .= '</tr>';
        $strTable .= '<tr style="font-weight:bold">';
        $strTable .= '<td colspan="15" style="height:35px;font-size:16px;">配送总单号：'.$duizhang_sn.'</td>';
        $strTable .= '</tr>';
        $strTable .= '<tr style="font-weight:bold">';
        $strTable .= '<td colspan="6" style="height:35px;">日期：&nbsp;&nbsp;&nbsp;年&nbsp;&nbsp;&nbsp;月&nbsp;&nbsp;&nbsp;日</td>';
        $strTable .= '<td colspan="2">姓名：  '.$driver.'</td>';
        $strTable .= '<td colspan="2">车牌：  </td>';
        $strTable .= '<td colspan="2">线路：  </td>';
        $strTable .= '<td colspan="3">订单数：'.count($orderList).'</td>';
        $strTable .= '</tr>';
        $strTable .= '<tr style="font-weight:bold">';
        $strTable .= '<td colspan="2" style="width:20px;height:35px;text-align:center">&nbsp;配送总金额&nbsp;</td>';
        $strTable .= '<td colspan="2" style="width:20px;text-align:center;word-break:break-all;">现金</td>';
        $strTable .= '<td colspan="4" style="text-align:center">转账</td>';
        $strTable .= '<td colspan="2" style="text-align:center">退货金额</td>';
        $strTable .= '<td colspan="5" style="text-align:center">未配送金额</td>';
        //$strTable .= '<td colspan="2">&nbsp;&nbsp;</td>';
        $strTable .= '</tr>';
        $strTable .= '<tr>';
        $strTable .= '<td colspan="2" style="height:35px;font-size:18px;text-align:center;font-weight: bold">￥'.$zongji.'</td>';
        $strTable .= '<td colspan="2"></td>';
        $strTable .= '<td colspan="2" style="font-size:16px;text-align:left;font-weight: bold"">应收:</td>';
        $strTable .= '<td colspan="2" style="font-size:16px;text-align:left;font-weight: bold"">实收:</td>';
        $strTable .= '<td colspan="2"></td>';
        $strTable .= '<td colspan="5"></td>';
        //$strTable .= '<td colspan="2"></td>';
        $strTable .= '</tr>';
        $strTable .= '<tr style="font-weight:bold">';
        $strTable .= '<td style="text-align:center;font-size:12px;width:5px;height:35px;">序号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:1px;">客户名</td>';
        $strTable .= '<td colspan="1" style="text-align:center;font-size:12px;width:1px;">合并单号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:42px;">订单号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:22px;">件数</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:80px;">商家名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:38px;">线路</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:15px;">小计金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:20px;">用户电话</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:20px;">用户地址</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:15px;">应收金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:15px;">礼品</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:15px;">合计金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:10px;">退货金额</td>';
        // $strTable .= '<td style="text-align:center;font-size:12px;width:50px;">POS机</td>';
//        $strTable .= '<td style="text-align:center;font-size:12px;width:50px;">&nbsp;现金</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:10px;">&nbsp;现金&nbsp;</td>';
        $strTable .= '</tr>';




        foreach($orderList as $vs){
            foreach($vs['order_list'] as $vss){
                $masterOrderSn[] = substr($vss['master_order_sn'],-7);
            }
        }
        $countValues = array_count_values($masterOrderSn);
//        print_r($orderList);exit;
        foreach($orderList as $vs){
            $strTables='';$i++;$tuihuo=0;
            foreach($vs['order_list'] as $key=>$vss){

                $master_count = $countValues[substr($vss['master_order_sn'],-7)];

                $fast_text = '';
                if($vss['fast_flag'] && $vss['store_fast_flag']){
                    $fast_text = "快";
                }
                // $tuilist=M('return_goods')->where('order_id='.$vss['order_id'])->select();
                // foreach($tuilist as $tv){
                // 	$tuihuo+=\sanwei($tv['member_goods_price']*$tv['goods_num']);
                // }


                $strTables .= '<tr>';
                if($key == 0){
                    $strTables .= '<td rowspan="'.$master_count.'" colspan="1"  style="text-align:center;font-size:12px;height:35px">&nbsp;'.substr($vss['master_order_sn'],-12).'</td>';
                }elseif($key != 0 && $vs['order_list'][$key-1]['master_order_sn'] != $vss['master_order_sn']){
                    $strTables .= '<td rowspan="'.$master_count.'" colspan="1" style="text-align:center;font-size:12px;height:35px">&nbsp;'.substr($vss['master_order_sn'],-12).'</td>';
                }
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px">&nbsp;'.substr($vss['order_sn'],-7).'</td>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px">'.$vss['jian_count'].'</td>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px">'.$vss['store_name'].'</td>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px">'.$vss['biaoshi_xian'].''.$fast_text.'</td>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px;color:red">'.$vss['total_amount'].'</td>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px;color:red">'.$vss['mobile'].'</td>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px;color:red">'.$vss['company_address'].'</td>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px;color:red">'.$vss['order_amount'].'</td>';
                $strTables .= '</tr>';
            }

//            // 获取首单日期的当天00:00:00
//            $firstOrderDateStart = strtotime(date('Y-m-d 00:00:00', $vs['first_order_time']));
//            // 获取首单日期的第二天23:59:59
//            $firstOrderDateEnd = strtotime(date('Y-m-d 23:59:59', strtotime('+1 day', $vs['first_order_time'])));

//            // 判断当前时间是否在首单日期的时间范围内
//            if (!empty($vs['first_order_time'])
//                && time() >= $firstOrderDateStart
//                && time() <= $firstOrderDateEnd) {
//                // 在此处添加需要显示首单金额
//                if (empty($vs['gift'])){
//                    $vs['gift'] = '首单金额：'.$vs['first_order_amount'].'元';
//                }else{
//                    $vs['gift'] .= '<br>首单金额：'.$vs['first_order_amount'].'元<br>';
//                }
//
//            }

            //首单金额
            //获取用户第一次下单的时间
             $first_date = M('order')->where(['user_id'=>$vs['user_id'],'order_status'=>['in','0,1,2']])->order('add_time asc')->limit(1)->getField('add_time');
            $order_today = date('Y-m-d',$first_date);
            $today = date('Y-m-d');//打印当天
            if ($order_today == $today){
                $todayStart = strtotime($order_today);
                $todayEnd = strtotime($order_today . ' 23:59:59');
                $first_order_amount = M('order')
                    ->where(['add_time'=>['between',"$todayStart,$todayEnd"],'order_status'=>['in','0,1,2'],'user_id'=>$vs['user_id']])
                    ->sum('order_amount');
                // 在此处添加需要显示首单金额
                if (empty($vs['gift'])){
                    $vs['gift'] = '首单金额：'.$first_order_amount.'元';
                }else{
                    $vs['gift'] .= '<br>首单金额：'.$first_order_amount.'元<br>';
                }
            }


            $strTable .= '<tr style="border:1px solid #000">
		<td style="text-align:center;font-size:12px;border:1px;width:5px;">'.$i.'</td>
		<td style="text-align:center;font-size:12px;border:1px;width:20px;WORD-WRAP:break-all;">'.$vs['company'].'</td>
		<td colspan="9">
		<table width="400" border="1">
            '.$strTables.'
		</table>
		</td>
		<td style="text-align:center;font-size:12px;color:red;font-weight:bold">'.$vs['gift'].'</td>
		<td style="text-align:center;font-size:12px;color:red;font-weight:bold">'.$vs['order_amount'].'</td>
		<td style="text-align:center;font-size:12px;color:red;font-weight:bold;color:green"></td>
		<td style="text-align:center;font-size:12px;color:red;font-weight:bold"></td>
		</tr>';
        }

        $strTable .= '<tr style="border:1px solid #000">
		<td colspan="7" style="text-align:right;font-weight:bold;height:32px">
		合计：
		</td>
		<td style="text-align:center;font-size:12px;color:red;font-weight:bold">'.$totalzongjia.'</td>
		<td style="text-align:center;font-size:12px;color:red;font-weight:bold"></td>
		<td style="text-align:center;font-size:12px;color:red;font-weight:bold"></td>
		<td style="text-align:center;font-size:12px;color:red;font-weight:bold">'.$zongji.'</td>
		<td style="text-align:center;font-size:12px;color:red;font-weight:bold"></td>
		</tr>';
        $strTable .='</table>';

        downloadExcel($strTable,'order');
        unset($orderList);
        exit();
    }

    /*
     * ajax 发货订单列表
    */
    public function ajaxdelivery(){
        $orderLogic = new OrderLogic();
        $condition = array();
        I('consignee') ? $condition['consignee'] = trim(I('consignee')) : false;
        I('order_sn') != '' ? $condition['order_sn'] = trim(I('order_sn')) : false;
        $condition['order_status'] = array('in','1,2,4');
        $shipping_status = I('shipping_status');
        $condition['shipping_status'] = empty($shipping_status) ? array('neq',1) : $shipping_status;
        $count = M('order')->where($condition)->count();
        $Page  = new AjaxPage($count,10);
        //搜索条件下 分页赋值
        foreach($condition as $key=>$val) {
            $Page->parameter[$key]   =   urlencode($val);
        }
        $show = $Page->show();
        $orderList = M('order')->where($condition)->limit($Page->firstRow.','.$Page->listRows)->order('add_time DESC')->select();
        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }

    /**
     * 订单详情
     * @param int $id 订单id
     */
    public function detail($order_id){
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        $button = $orderLogic->getOrderButton($order);
        // 获取操作记录
        $action_log = M('order_action')->where(array('order_id'=>$order_id))->order('log_time desc')->select();
         foreach ($action_log as $k=>$v){
            if(empty($v['store_id']) && empty($v['admin_id'])){
                $action_log[$k]['user'] = '用户';
                $action_log[$k]['user_name'] = M('users')->where(['user_id'=>$v['action_user']])->getField('company');
            }
            if($v['store_id'] >0 && empty($v['admin_id'])){
                $action_log[$k]['user'] = '商家';
                $action_log[$k]['user_name'] = M('store')->where(['store_id'=>$v['store_id']])->getField('store_name');
            }
            if($v['admin_id'] >0 ){
                $action_log[$k]['user'] = '总后台';
                $action_log[$k]['user_name'] = M('admin')->where(['admin_id'=>$v['admin_id']])->getField('user_name');
            }
        }
        $order['jian_list']=M('order_jian')->where(array('order_id'=>$order_id))->order('id asc')->select();

        $split = count($orderGoods) >1 ? 1 : 0;
        $points=$points_count=0;
        foreach ($orderGoods as $key=>$val){
            $spec_img = M('spec_image')->where(['spec_image_id'=>$val['spec_key']])->getField('src');
            if($spec_img){
                $orderGoods[$key]['original_img'] =  C('MYOSS')['url2'].$spec_img;
            }else{
                $orderGoods[$key]['original_img'] =  C('MYOSS')['url2'].$val['original_img'];
            }

            if($val['goods_num']>=1){
                $split = 1;
                $points_count+=\sanwei($val['points']*($val['member_goods_price']-$val['yijia'])*$val['goods_num']/100);
            }
        }
        $this->assign('order',$order);
        $this->assign('action_log',$action_log);
        $this->assign('orderGoods',$orderGoods);
        $this->assign('points_count',$points_count);
        $this->assign('split',$split);$this->assign('z',$this->z);
        $this->assign('button',$button);
        $this->display();
    }

    /**
     * 订单编辑
     * @param int $id 订单id
     */
    public function edit_order(){
        $order_id = I('order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        // if($order['shipping_status'] != 0){
        //     $this->error('已发货订单不允许编辑');
        //     exit;
        // }

        $orderGoods = $orderLogic->getOrderGoods($order_id);

        if(IS_POST)
        {
            if(I('admin_note') == ''){
                $this->error('改单说明不能为空！');
                exit;
            }
            $ordern=M('order')->where('order_id='.$order_id)->find();
            $order['consignee'] = I('consignee');// 收货人
            $order['province'] = I('province'); // 省份
            $order['city'] = I('city'); // 城市
            $order['district'] = I('district'); // 县
            $order['address'] = I('address'); // 收货地址
            $order['mobile'] = I('mobile'); // 手机
            $order['goods_price'] = $ordern['goods_price']; // 重写价格
            $order['order_amount'] =$ordern['order_amount']; // 重写价格
            $order['invoice_title'] = I('invoice_title');// 发票
            $order['admin_note'] = I('admin_note'); // 管理员备注
            $order['shipping_code'] = I('shipping');// 物流方式
            $order_status = I('order_status');// 状态
            $order['shipping_name'] = M('plugin')->where(array('status'=>1,'type'=>'shipping','code'=>I('shipping')))->getField('name');
            $order['pay_code'] = I('payment')??'cod';// 支付方式
            $order['pay_name'] = M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>$order['pay_code']))->getField('name');
            $goods_id_arr = I("goods_id");

            //################################修改订单费用
            $order['order_status'] = $order_status; // 订单状态
            if($order['order_status'] == 0){
                $order['shipping_status'] = 0;
                M('order_jian')->where(['order_id'=>$order['order_id']])->delete();
            }elseif($order['order_status'] == 1 ){
                $order['shipping_status'] = 1;
            }
            $o = M('order')->where('order_id='.$order_id)->save($order);
            //获取原本的订单状态，如果原订单不是取消和作废的就进去增加库存
            if($ordern['order_status'] != 3 && $ordern['order_status'] != 5){
                if($order_status == 3 || $order_status == 5){
                    $orderGoods = M('order_goods')->where(['order_id'=>$ordern['order_id']])->select();
                    foreach ($orderGoods as $k=>$v){
                        M('spec_goods_price')->where(['key'=>$v['spec_key']])->setInc('store_count',$v['goods_num']);
                    }
                    //如果是积分订单就退还积分
                    if($ordern['order_prom_type'] == 101){
                        M('users')->where('user_id='.$ordern['user_id'])->setInc('pay_points',$ordern['integral']);
                    }
                }
            }else{
                //原订单是取消作废的进来改作废和取消不懂，改其他的减少库存
               if($order_status == 3 || $order_status == 5){
                    M('users_price')->where('order_id='.$ordern['order_id'])->setField(['price'=>0]);
                }else{
                    $orderGoods = M('order_goods')->where(['order_id'=>$ordern['order_id']])->select();
                    foreach ($orderGoods as $k=>$v){
                        M('spec_goods_price')->where(['key'=>$v['spec_key']])->setDec('store_count',$v['goods_num']);
                    }
                }
            }
            
            $admin_id = session('admin_id'); // 当前操作的管理员
            $l = $orderLogic->orderActionLog($order_id,'edit','修改订单',$admin_id);//操作日志
            if($o && $l){
                $this->success('修改成功',U('Admin/Order/edit_order',array('order_id'=>$order_id)));
            }else{
                $this->success('修改失败',U('Admin/Order/detail',array('order_id'=>$order_id)));
            }
            exit;
        }
        // 获取省份
        $province = M('region')->where(array('parent_id'=>0,'level'=>1))->select();
        //获取订单城市
        $city =  M('region')->where(array('parent_id'=>$order['province'],'level'=>2))->select();
        //获取订单地区
        $area =  M('region')->where(array('parent_id'=>$order['city'],'level'=>3))->select();
        //获取支付方式
        $payment_list = M('plugin')->where(array('status'=>1,'type'=>'payment'))->select();
        //获取配送方式
        $shipping_list = M('plugin')->where(array('status'=>1,'type'=>'shipping'))->select();

        $this->assign('order',$order);
        $this->assign('province',$province);
        $this->assign('city',$city);
        $this->assign('area',$area);
        $this->assign('orderGoods',$orderGoods);
        $this->assign('shipping_list',$shipping_list);
        $this->assign('payment_list',$payment_list);
        $this->display();
    }

    /*
     * 拆分订单
     */
    public function split_order(){
        $order_id = I('order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        if($order['shipping_status'] != 0){
            $this->error('已发货订单不允许编辑');
            exit;
        }
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        if(IS_POST){
            $data = I('post.');
            //################################先处理原单剩余商品和原订单信息
            $old_goods = I('goods');
            foreach ($orderGoods as $val){
                if(empty($old_goods[$val['rec_id']])){
                    M('order_goods')->where("rec_id=".$val['rec_id'])->delete();//删除商品
                }else{
                    //修改商品数量
                    if($old_goods[$val['rec_id']] != $val['goods_num']){
                        $val['goods_num'] = $old_goods[$val['rec_id']];
                        M('order_goods')->where("rec_id=".$val['rec_id'])->save(array('goods_num'=>$val['goods_num']));
                    }
                    $oldArr[] = $val;//剩余商品
                }
                $all_goods[$val['rec_id']] = $val;//所有商品信息
            }
            $result = calculate_price($order['user_id'],$oldArr,$order['shipping_code'],0,$order['province'],$order['city'],$order['district'],0,0,0,0,0,11);
            if($result['status'] < 0)
            {
                $this->error($result['msg']);
            }
            //修改订单费用
            $res['goods_price']    = $result['result']['goods_price']; // 商品总价
            $res['order_amount']   = $result['result']['order_amount']; // 应付金额
            $res['total_amount']   = $result['result']['total_amount']; // 订单总价
            M('order')->where("order_id=".$order_id)->save($res);
            //################################原单处理结束

            //################################新单处理
            for($i=1;$i<20;$i++){
                if(empty($_POST[$i.'_goods'])){
                    break;
                }else{
                    $split_goods[] = $_POST[$i.'_goods'];
                }
            }

            foreach ($split_goods as $key=>$vrr){
                foreach ($vrr as $k=>$v){
                    $all_goods[$k]['goods_num'] = $v;
                    $brr[$key][] = $all_goods[$k];
                }
            }

            foreach($brr as $goods){
                $result = calculate_price($order['user_id'],$goods,$order['shipping_code'],0,$order['province'],$order['city'],$order['district'],0,0,0,0,0,11);
                if($result['status'] < 0)
                {
                    $this->error($result['msg']);
                }
                $new_order = $order;
                $new_order['order_sn'] = date('YmdHis').mt_rand(1000,9999);
                $new_order['parent_sn'] = $order['order_sn'];
                //修改订单费用
                $new_order['goods_price']    = $result['result']['goods_price']; // 商品总价
                $new_order['order_amount']   = $result['result']['order_amount']; // 应付金额
                $new_order['total_amount']   = $result['result']['total_amount']; // 订单总价
                $new_order['add_time'] = time();
                unset($new_order['order_id']);
                $new_order_id = M('order')->add($new_order);//插入订单表
                foreach ($goods as $vv){
                    $vv['order_id'] = $new_order_id;
                    $nid = M('order_goods')->add($vv);//插入订单商品表
                }
            }
            //################################新单处理结束
            $this->success('操作成功',U('Admin/Order/detail',array('order_id'=>$order_id)));
            exit;
        }

        foreach ($orderGoods as $val){
            $brr[$val['rec_id']] = array('goods_num'=>$val['goods_num'],'goods_name'=>getSubstr($val['goods_name'], 0, 35).$val['spec_key_name']);
        }
        $this->assign('order',$order);
        $this->assign('goods_num_arr',json_encode($brr));
        $this->assign('orderGoods',$orderGoods);
        $this->display();
    }

    /*
     * 价钱修改
     */
    public function editprice($order_id){
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        //$this->editable($order);
        if(IS_POST){
            $admin_id = session('admin_id');
            if(empty($admin_id)){
                $this->error('非法操作');
                exit;
            }
            $update['discount'] = I('post.discount');
            $update['shipping_price'] = I('post.shipping_price');
            $update['order_amount'] = $order['goods_price'] + $update['shipping_price'] + $update['discount'] - $order['user_money'] - $order['integral_money'] - $order['coupon_price'];
            $row = M('order')->where(array('order_id'=>$order_id))->save($update);
            if(!$row){
                $this->success('没有更新数据',U('Admin/Order/editprice',array('order_id'=>$order_id)));
            }else{
                $this->success('操作成功',U('Admin/Order/detail',array('order_id'=>$order_id)));
            }
            exit;
        }
        $this->assign('order',$order);
        $this->display();
    }

    /**
     * 订单删除
     * @param int $id 订单id
     */
    public function delete_order($order_id,$store_id){
        $orderLogic = new OrderLogic();
        $del = $orderLogic->delOrder($order_id,$store_id);
        if($del){
            $this->success('删除订单成功');
        }else{
            $this->error('订单删除失败,订单状态必须是“作废”才能删除！');
        }
    }

    /**
     * 订单取消付款
     */
    public function pay_cancel($order_id){
        if(I('remark')){
            $data = I('post.');
            $note = array('退款到用户余额','已通过其他方式退款','不处理，误操作项');
            if($data['refundType'] == 0 && $data['amount']>0){
                accountLog($data['user_id'], $data['amount'], 0,  '退款到用户余额');
            }
            $orderLogic = new OrderLogic();
            $admin_id = session('admin_id'); // 当前操作的管理员
            $d = $orderLogic->orderActionLog($data['order_id'],'pay_cancel',$data['remark'].':'.$note[$data['refundType']],$admin_id);
            if($d){
                exit("<script>window.parent.pay_callback(1);</script>");
            }else{
                exit("<script>window.parent.pay_callback(0);</script>");
            }
        }else{
            $order = M('order')->where("order_id=$order_id")->find();
            $this->assign('order',$order);
            $this->display();
        }
    }

    /**
     * 订单打印
     * @param int $id 订单id
     */
    public function order_print($user_id=0){
        // 搜索条件
        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        $user_id=trim(I('user_id'));
        $action=trim(I('action'));
        if($action=="yes" && I('order_id')!=''){
            M('order')->where('order_id='.I('order_id'))->setInc('dayin_num');
            exit;
        }
   
        
        $orderList =  M('users')->field('user_id,nickname,mobile,company_address,biaoshi,biaoshi_xian,company')
            //->join('ty_users b on a.user_id=b.user_id','LEFT')
            ->where(['user_id'=>['in',$user_id]])->order('xsort asc')->select(); //过滤获取主订单
        $userStoreGifts = [];
        foreach($orderList as $key=>$v){
            $userGifts = [];
            $order_list=M('order a')
                ->field('a.add_time,a.order_id,a.coupon_price,a.pay_status,a.order_sn,a.store_id,a.order_amount,a.jian_count,a.admin_note,a.user_note,a.discount,a.yijia_heji,b.ruku_time')
                ->join('ty_order_jian b on b.order_id=a.order_id','LEFT')
                ->join('ty_users c on a.user_id=c.user_id','LEFT')
                ->where('a.user_id ='.$v['user_id'].' and a.order_status=1 and a.jian_count >0 and a.ruku_count = a.jian_count and a.chuku_count <> a.ruku_count and a.shipping_status=1 and b.status_r=1 and b.status_c!=1 and a.ruku_last_time < '.$end.' and a.ruku_last_time > '.$begin)
                ->order('c.xsort asc')
                ->group('a.order_id')
                ->select();
//            dump($order_list);
            $orderList[$key]['fast_flag'] = $v['fast_flag'] ? '快' : '';
            if($order_list){
                $orderList[$key]["order_id"]=$order_list[0]['order_id'];
                $orderList[$key]["order_list"]=$order_list;
                foreach($order_list as $keys=>$values){ //整理子单产品
                    if(empty($values['coupon_price'])){
                        $values['coupon_price'] = 0;
                    }
                    $orderList[$key]["order_list"][$keys]["coupon_price"] = sanwei($values['coupon_price']);
                    $orderList[$key]["order_list"][$keys]["ruku"]=M('order_jian')->where('order_id='.$values['order_id'].' and '.$this->z.'status_r=1')->count();
                    $orderList[$key]["order_list"][$keys]["chuku"]=M('order_jian')->where('order_id='.$values['order_id'].' and '.$this->z.'status_c=1')->count();

                    $orderList[$key]["order_list"][$keys]["g_list"]=M('order_goods a')->field('a.*,b.original_img')->join('ty_goods b ON a.goods_id = b.goods_id')->where(array('a.order_id'=>$values['order_id']))->select();
                    foreach ($orderList[$key]["order_list"][$keys]["g_list"] as $kk=>$vv){
                        if($vv['prom_type'] == 4){
                            //查看满赠活动多送
                            $goodsfull = M('prom_goods')->where(['id'=>$vv['prom_id']])->find();

                            if($goodsfull['type'] == 4){
                                $goods_key = json_decode($goodsfull['goods_key'],true);
                                $full = explode('/',$goodsfull['expression']);
                                $goodsfull['goods_num'] = $full[0];
                                $goodsfull['send_num'] = $full[1];
                                if(in_array($vv['spec_key'],$goods_key)){
                                    $msg = '满'.$goodsfull['goods_num'].'送'.$goodsfull['send_num'];
                                    //存在这个满赠活动多送的情况先，修改order_goods
                                    $freeQuantity = floor(floatval($vv['goods_num']) / $goodsfull['goods_num']) * $goodsfull['send_num'];// 计算赠送商品数量，使用 floor 函数取整数部分

                                    if($freeQuantity > 0){
                                        // $orderGoods[$k]['goods_num'] = floatval($v['goods_num']).'+'.$freeQuantity;
                                        // $orderGoods[$k]['goods_name'] = $v['goods_name'].'('.$msg.')';
                                        // 获取 DRIVER_SET 数组最后一个键
                                        $lastKey = end(array_keys($orderList[$key]["order_list"][$keys]["g_list"]));
                                        // 解析最后一个键的数字部分
//                                        $lastNumber = (int) substr($lastKey, 2);
                                        // 生成新的键
//                                        $newKey = sprintf('%03d', $lastNumber + 1);
                                        $newKey = $lastNumber + 1;
                                        // 复制最后一行数据
                                        $newData = $orderList[$key]["order_list"][$keys]["g_list"][$kk];
                                        // 将复制的数据添加到 DRIVER_SET 数组末尾
                                        $newData['goods_num'] = $freeQuantity;
                                        $newData['goods_name'] = $vv['goods_name'].'('.$msg.')';
                                        $newData['member_goods_price'] = 0;
                                        $newData['goods_kou_total'] = 0;
                                        $orderList[$key]["order_list"][$keys]["g_list"][$newKey] = $newData;
                                    }


                                }
                            }
                        }
                    }

                    //循环获取商家每日满赠活动
                    $activity = M('goods_full')->where([
                        'store_id' => $values['store_id'],
                        'start_time' => ['elt', time()],
                        'end_time' => ['egt', time()]
                    ])->order('id desc')->find();
                    if ($activity) {
                        
                        $where = [];
                        if(!empty($activity['brand_id'])){
                            $brand_id = implode(',',json_decode($activity['brand_id'],true));
                            $where['gs.store_cat_id1'] = ['in',$brand_id];
                        }
                        if(!empty($activity['goods_id'])){
                            $goods_id = implode(',',json_decode($activity['goods_id'],true));
                            $where['gs.goods_id'] = ['in',$goods_id];
                        }
                        
                        
                        // 获取当天用户下单总金额
                        // $todayStart = strtotime(date('Y-m-d 00:00:00',$values['add_time']));
                        // $todayEnd = strtotime(date('Y-m-d 23:59:59',$values['add_time']));
                        if($activity['type'] == 1){
                            // 获取当天用户下单总金额
                            $todayStart = strtotime('midnight', $values['add_time']);
                            $todayEnd = strtotime('tomorrow', $values['add_time']) - 1;
                        }else{
                            // 获取这个时间区间的
                            $todayStart = $activity['start_time'];
                            $todayEnd = $activity['end_time'];
                        } 
                      
                        $where['o.user_id'] = $v['user_id'];
                        $where['o.order_status'] = ['in','0,1,2'];
                        $where['o.store_id'] = $values['store_id'];
                        $where['g.full_status'] = 0;
                        $where['o.add_time'] = ['between', [$todayStart, $todayEnd]];
                        
                        $totalAmount = M('order_goods g')
                	    ->join('ty_order o on o.order_id = g.order_id','left')
                	    ->join('ty_goods gs on gs.goods_id = g.goods_id','left')
                	    ->where($where)->sum('(g.member_goods_price+g.yijia)*goods_num');
                        // dump($totalAmount);
                        // dump($v['user_id']);
                        // dump($values['store_id']);
                        if(empty($totalAmount)){
                            $totalAmount = 0;
                        }
                        $storeUserId = $v['user_id'].'_'.$values['store_id'];
                      
                         // 判断是否达到活动条件
                        if (!empty($storeUserId)) {
                            $finalGift = null;
                            $gifts = json_decode($activity['full_gift'], true);
                            usort($gifts, function($a, $b) {
                                return $b['price'] <=> $a['price'];
                            });
                            foreach ($gifts as $gift) {
                                if ($totalAmount >= $gift['price']) {
                                    $finalGift = $gift['gift'];
                                    break;
                                }
                            }
                            
                            // 将赠品信息存储在用户级别
                            // $userGifts[$v['user_id']] = $finalGift;
                            $userStoreGifts[$storeUserId] = $finalGift;
                        }
                        // // 判断是否达到活动条件
                        // $finalGift = null;
                        // $gifts = json_decode($activity['full_gift'], true);
                        // usort($gifts, function($a, $b) {
                        //     return $b['price'] <=> $a['price'];
                        // });
                        // foreach ($gifts as $gift) {
                        //     if ($totalAmount >= $gift['price']) {
                        //         $finalGift = $gift['gift'];
                        //         break;
                        //     }
                        // }
                        // dump($finalGift);
                        // if($finalGift){
                        //     $orderList[$key]["order_list"][$keys]['gift'] = '赠品：'.$finalGift;
                        // }
                     
                         // 只在当前商家的第一个订单显示赠品
                        if ($userStoreGifts[$storeUserId] && empty($shownGifts[$storeUserId])) {
                            $orderList[$key]["order_list"][$keys]['gift'] = '赠品：'.$userStoreGifts[$storeUserId];
                            $shownGifts[$storeUserId] = true;
                        } else {
                            
                            $orderList[$key]["order_list"][$keys]['gift'] = '';
                        }
                        
                    }else{
                        $orderList[$key]["order_list"][$keys]['gift'] = '';

                    }
                }
            }else{
                unset($orderList[$key]);
            }
        }
//        dump($orderList);
        //echo \json_encode($orderList);exit;

        $store_list = M('store')->getField('store_id,store_name');
        $this->assign('store_list',$store_list);
        $this->assign('orderList',$orderList);
        $this->display('print');
    }

    /**
     * 退货单订单打印
     * @param int $id 订单id
     */
    public function return_print($ids=0){
        // // 搜索条件
        // $ids=trim(I('ids'));

        // $orderList = M('return_goods a')
        //     ->field('a.*,(a.member_goods_price+a.yijia) member_goods_price,b.*,c.original_img as imgs,c.goods_name,d.store_name,e.key_name')
        //     ->join('ty_users b ON a.user_id = b.user_id','LEFT')
        //     ->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
        //     ->join('ty_store d ON a.store_id = d.store_id','LEFT')
        //     ->join('ty_spec_goods_price e ON a.spec_key = e.key','LEFT')
        //     ->where('a.id in ('.$ids.')')->order('a.id desc')->select();
        // $this->assign('orderList',$orderList);
        $order_ids = I('ids');
        if(empty($order_ids))
            $this->error('非法操作！');

        // 搜索条件
        $orderLogic = new OrderLogic();
        $orders = M('return_goods a')
            ->field('a.*,b.mobile,b.company,b.biaoshi,b.biaoshi_xian,b.fast_flag,b.company_address,c.store_name,c.store_phone,(member_goods_price+yijia) as member_goods_price,b.fast_flag ,c.fast_flag as store_fast_flag')
            ->join('ty_users b on a.user_id=b.user_id')
            ->join('ty_store c on a.store_id=c.store_id')
            ->where("a.id in($order_ids)")->order('a.id desc')->select();

        $print_data=[];
        foreach($orders as $key=>$vs){
            if(!$vs['spec_key']){
                $this->error('sku被商家删除');
            }
            $store=M('store')->where("store_id=".$vs['store_id'])->find();
            //批量打印单据
            if($vs['order_id']){
                $orders[$key]['tuihuo_qr'] = tuihuoQRcode($vs,'self',1);
                // $orders[$key]['full_address'] = getRegionName($vs['province']).' '.getRegionName($vs['city']).' '.getRegionName($vs['district']).' '. $vs['address'];
                $orders[$key]['g_list'] =M('order_goods')->where('order_id='.$vs['order_id'].' and goods_id='.$vs['goods_id'].' and spec_key= "'.$vs['spec_key'].'" ')->find();

                update_user_level($vs['user_id']);
                foreach ($orders[$key]['g_list'] as $k=>$item){
                    $orders[$key]['g_list']['member_goods_price'] = sanwei($vs['member_goods_price']);
                }

                $print_data[]=[
                    'jian_count'=>$vs['jian_count'],
                    'id'=>$vs['id'],
                    'biaoshi'=>$vs['biaoshi']?$vs['biaoshi']:'',
                    'biaoshi_xian'=>$vs['biaoshi_xian'],
                    'order_sn'=>$vs['order_sn'],
                    'company'=>$vs['company'],
                    'fast_text'=>$vs['fast_flag'] && $vs['store_fast_flag'] ? "快线" : "",
                    'goods_num'=>$vs['goods_num'],
                    'tuihuo_qr'=>tuihuoQRcode($vs,'self',1),
                    'mobile'=>$vs['mobile'], //$vs['mobile'],
                    'company_address'=>$vs['company_address'],
                    'g_list'=>$orders[$key]['g_list'],
                    'total_amount'=>\sanwei($vs['goods_num']*$vs['member_goods_price']),
                    'member_goods_price'=>\sanwei($vs['member_goods_price']),
                    'store_name'=>$store['store_name'],
                    'store_phone'=>$store['store_phone'],
                    'user_note'=>$vs['user_note'],
                    'xiaoji'=>$vs['user_note'],
                    'siji'=>M('users')->where('user_id='.$vs['driver_id'])->getField('nick_name'),
                    'tuihuo_time'=>date("Y-m-d H:i",$vs['tuihuo_time'])
                ];
            }
        }
        $this->assign('orders',$orders);
        $this->assign('print_t',session('print_t'));
        $this->assign('print_data',\json_encode($print_data));
        $this->display('return_print');
    }

    /**
     * 退货单订单打印
     * @param int $id 订单id
     */
    public function return_print2(){
        // // 搜索条件
        // $ids=trim(I('ids'));

        // $orderList = M('return_goods a')
        //     ->field('a.*,(a.member_goods_price+a.yijia) member_goods_price,b.*,c.original_img as imgs,c.goods_name,d.store_name,e.key_name')
        //     ->join('ty_users b ON a.user_id = b.user_id','LEFT')
        //     ->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
        //     ->join('ty_store d ON a.store_id = d.store_id','LEFT')
        //     ->join('ty_spec_goods_price e ON a.spec_key = e.key','LEFT')
        //     ->where('a.id in ('.$ids.')')->order('a.id desc')->select();
        // $this->assign('orderList',$orderList);
        $return_order_sn = I('ids');
        if($return_order_sn == 'tuihuo_qr'){
            return;
        }
        // dump($return_order_sn);
        if(empty($return_order_sn))
            $this->error('非法操作！');

        // 搜索条件


        $orders = M('return_goods a')
            ->field('a.*,b.mobile,b.company,b.biaoshi,b.biaoshi_xian,b.fast_flag,b.company_address,c.store_name,c.store_phone,(member_goods_price+yijia) as member_goods_price,b.fast_flag ,c.fast_flag as store_fast_flag')
            ->join('ty_users b on a.user_id=b.user_id')
            ->join('ty_store c on a.store_id=c.store_id')
//            ->where("a.return_order_sn in (".$return_order_sn.") and a.status <> 3")
            ->where(['a.return_order_sn'=>[['in',$return_order_sn]],'a.status'=>['neq',3]])
            ->order('a.id desc')->select();
       

       
        $orders = group_same_key($orders,'return_order_sn');
        $orders = array_values($orders);
    
        $print_data=[];
        $return_data=[];
        foreach($orders as $key=>$vv){
            $return_ids = array_column($vv,'id');
            $sum = 0;
            $sum2 = 0;
            $zongcoupon_price = 0;
             
        
        
          foreach ($vv as $kk=>$vs){
              if(!$vs['spec_key']){
                  $this->error('sku被商家删除');
              }
              $store=M('store')->where("store_id=".$vs['store_id'])->find();
              //批量打印单据
              if($vs['order_id']){
                  $orderInfo = M('order')->where(['order_id'=>$vs['order_id']])->find();
                  $total_amount = $orderInfo['total_amount'];//总价
                  $coupon_price = $orderInfo['coupon_price'];//优惠价
                  
                  $return_data[$key]['id'] = join(',',$return_ids);
                  $return_data[$key]['order_id'] = $vv[0]['order_id'];
                  $return_data[$key]['order_sn'] = $vv[0]['return_order_sn'];
                  $return_data[$key]['order_sn2'] = $vv[0]['order_sn'];
                  $return_data[$key]['addtime'] = $vv[0]['addtime'];
                  $return_data[$key]['tuihuo_time'] = $vv[0]['tuihuo_time'];
                  $return_data[$key]['remark'] = $vv[0]['remark'];
                  $return_data[$key]['store_id'] = $vv[0]['store_id'];
                  $return_data[$key]['driver_id'] = $vv[0]['driver_id'];
                  $return_data[$key]['siji'] = M('users')->where('user_id='.$vv[0]['driver_id'])->getField('nick_name');
                  $return_data[$key]['mobile'] = $vv[0]['mobile'];
                  $return_data[$key]['company'] = $vv[0]['company'];
                  $return_data[$key]['biaoshi'] = $vv[0]['biaoshi'];
                  $return_data[$key]['biaoshi_xian'] = $vv[0]['biaoshi_xian'];
                  $return_data[$key]['fast_flag'] = $vv[0]['fast_flag'];
                  $return_data[$key]['company_address'] = $vv[0]['company_address'];
                  $return_data[$key]['store_name'] = $vv[0]['store_name'];
                  $return_data[$key]['store_phone'] = $vv[0]['store_phone'];
                  $return_data[$key]['store_fast_flag'] = $vv[0]['store_fast_flag'];
                  $return_data[$key]['tuihuo_qr'] = tuihuoQRcode(['id'=>join(',',$return_ids)],'self',1);
                  $return_data[$key]['goodsLength'] = count($return_data[$key]['g_list']);
                
                  $goods = M('order_goods')->where('order_id='.$vs['order_id'].' and goods_id='.$vs['goods_id'].' and spec_key= "'.$vs['spec_key'].'" ')->find();
                  if($coupon_price>0){
                         //算出这个退货单在这里占多少
                        $Proportion = ($vs['member_goods_price'] * $vs['goods_num'])/$total_amount;
                        //算出优惠金额
                        $return_data[$key]['g_list'][$kk]['coupon_price'] = geshi($Proportion*$coupon_price);
                    }else{
                        $return_data[$key]['g_list'][$kk]['coupon_price'] = 0;
                    }
                  $return_data[$key]['g_list'][$kk]['member_goods_price'] = sanwei($vs['member_goods_price']);
                  $return_data[$key]['g_list'][$kk]['goods_num'] = $vs['goods_num'];
                  $return_data[$key]['g_list'][$kk]['points'] = $vs['points'];
                  $return_data[$key]['g_list'][$kk]['goods_name'] = $goods['goods_name'];
                  $return_data[$key]['g_list'][$kk]['spec_key_name'] = $goods['spec_key_name'];
                  $return_data[$key]['g_list'][$kk]['xiaoji'] = sanwei(($vs['member_goods_price'] * $vs['goods_num'])-$return_data[$key]['g_list'][$kk]['coupon_price']);
                  $return_data[$key]['g_list'][$kk]['yuanjia'] = sanwei($vs['member_goods_price'] * $vs['goods_num']);
                
                
                
                
                  $sum+= ($vs['member_goods_price'] * $vs['goods_num'])-$return_data[$key]['g_list'][$kk]['coupon_price'];
                  $sum2+= $vs['member_goods_price'] * $vs['goods_num'];
                  $zongcoupon_price += $return_data[$key]['g_list'][$kk]['coupon_price'];
                  $return_data[$key]['return_sum'] = sanwei($sum);
                  $return_data[$key]['return_sum2'] = sanwei($sum2);
                  $return_data[$key]['zongcoupon_price'] = sanwei($zongcoupon_price);
//                  $orders[$key]['tuihuo_qr'] = tuihuoQRcode($vs,'self',1);
                  // $orders[$key]['full_address'] = getRegionName($vs['province']).' '.getRegionName($vs['city']).' '.getRegionName($vs['district']).' '. $vs['address'];
//                  $orders[$key]['g_list'] =M('order_goods')->where('order_id='.$vs['order_id'].' and goods_id='.$vs['goods_id'].' and spec_key= "'.$vs['spec_key'].'" ')->find();

                  update_user_level($vs['user_id']);
//                  foreach ($orders[$key]['g_list'] as $k=>$item){
//                      $orders[$key]['g_list']['member_goods_price'] = sanwei($vs['member_goods_price']);
//                  }

                  $print_data[$key]=[
                      'id'=>join(',',$return_ids),
                      'biaoshi'=>$vv[0]['biaoshi']?$vv[0]['biaoshi']:'',
                      'biaoshi_xian'=>$vv[0]['biaoshi_xian'],
                      'order_sn'=>$vv[0]['return_order_sn'],
                      'order_sn2'=>$vv[0]['order_sn'],
                      'company'=>$vv[0]['company'],
                      'fast_text'=>$vv[0]['fast_flag'] && $vv[0]['store_fast_flag'] ? "快线" : "",
                      'goods_num'=>$vv[0]['goods_num'],
                      'tuihuo_qr'=>tuihuoQRcode(['id'=>join(',',$return_ids)],'self',1),
                      'mobile'=>$vv[0]['mobile'], //$vs['mobile'],
                      'company_address'=>$vv[0]['company_address'],
                      'g_list'=>$return_data[$key]['g_list'],
                      'total_amount'=>\sanwei($sum),
                      'zongjia'=>\sanwei($sum2),
                      'coupon_price'=>\sanwei($zongcoupon_price),
//                      'member_goods_price'=>\sanwei($vs['member_goods_price']),
                      'store_name'=>$vv[0]['store_name'],
                      'store_phone'=>$vv[0]['store_phone'],
//                      'user_note'=>$vs['user_note'],
//                      'xiaoji'=>$vs['user_note'],
                      'siji'=>M('users')->where('user_id='.$vv[0]['driver_id'])->getField('nick_name'),
                      'tuihuo_time'=>date("Y-m-d H:i",$vv[0]['tuihuo_time']),
                      'goodsLength'=>$return_data[$key]['goodsLength']
                  ];
              }
          }
        }


        $this->assign('orders',$return_data);
        $this->assign('print_t',session('print_t'));

        $this->assign('print_data',\json_encode($print_data));
        $this->display('return_print2');
    }

    /**
     * 订单打印
     * @param int $id 订单id
     */
    public function order_prints(){
        $order_id = I('order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $order['province'] = getRegionName($order['province']);
        $order['city'] = getRegionName($order['city']);
        $order['district'] = getRegionName($order['district']);
        $order['full_address'] = $order['province'].' '.$order['city'].' '.$order['district'].' '. $order['address'];
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        foreach ($orderGoods as $k=>$v){
            if($v['prom_id'] != 0){
                $prom = M('prom_goods')->where(['id'=>$v['prom_id']])->find();
                if(time() > $prom['start_time'] && time() < $prom['end_time']){
                    $orderGoods[$k]['huodong'] = '(活动商品)';
                }
            }
        }
        
        $fast_flag = M('users')->where("user_id=".$order['user_id'])->getField('fast_flag');
        if($fast_flag){
            $fast_text = '快';
        }else{
            $fast_text = '';
        }
        $shop = tpCache('shop_info');
        $this->assign('order',$order);
        $this->assign('users',M('users')->where("user_id=".$order['user_id'])->find());
        update_user_level($order['user_id']);
        $this->assign('shop',$shop);
        $this->assign('fast_text',$fast_text);
        $this->assign('store',M('store')->where("store_id=".$order['store_id'])->find());
        $this->assign('orderGoods',$orderGoods);
        $template = I('template','order_prints');
        $this->display($template);
    }

    /**
     * 快递单打印
     */
    public function shipping_print(){
        $order_id = I('get.order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        //查询是否存在订单及物流
        $shipping = M('plugin')->where(array('code'=>$order['shipping_code'],'type'=>'shipping'))->find();
        if(!$shipping){
            $this->error('物流插件不存在');
        }
        if(empty($shipping['config_value'])){
            $this->error('请设置'.$shipping['name'].'打印模板');
        }
        $shop = tpCache('shop_info');//获取网站信息
        $shop['province'] = empty($shop['province']) ? '' : getRegionName($shop['province']);
        $shop['city'] = empty($shop['city']) ? '' : getRegionName($shop['city']);
        $shop['district'] = empty($shop['district']) ? '' : getRegionName($shop['district']);

        $order['province'] = getRegionName($order['province']);
        $order['city'] = getRegionName($order['city']);
        $order['district'] = getRegionName($order['district']);
        if(empty($shipping['config'])){
            $config = array('width'=>840,'height'=>480,'offset_x'=>0,'offset_y'=>0);
            $this->assign('config',$config);
        }else{
            $this->assign('config',unserialize($shipping['config']));
        }
        $template_var = array("发货点-名称", "发货点-联系人", "发货点-电话", "发货点-省份", "发货点-城市",
            "发货点-区县", "发货点-手机", "发货点-详细地址", "收件人-姓名", "收件人-手机", "收件人-电话",
            "收件人-省份", "收件人-城市", "收件人-区县", "收件人-邮编", "收件人-详细地址", "时间-年", "时间-月",
            "时间-日","时间-当前日期","订单-订单号", "订单-备注","订单-配送费用");
        $content_var = array($shop['store_name'],$shop['contact'],$shop['phone'],$shop['province'],$shop['city'],
            $shop['district'],$shop['phone'],$shop['address'],$order['consignee'],$order['mobile'],$order['phone'],
            $order['province'],$order['city'],$order['district'],$order['zipcode'],$order['address'],date('Y'),date('M'),
            date('d'),date('Y-m-d'),$order['order_sn'],$order['admin_note'],$order['shipping_price'],
        );
        $shipping['config_value'] = str_replace($template_var,$content_var, $shipping['config_value']);
        $this->assign('shipping',$shipping);
        $this->display("Plugin/print_express");
    }

    /**
     * 生成发货单
     */
    public function deliveryHandle(){
        $orderLogic = new OrderLogic();
        $data = I('post.');
        $res = $orderLogic->deliveryHandle($data);
        if($res){
            $this->success('操作成功',U('Admin/Order/delivery_info',array('order_id'=>$data['order_id'])));
        }else{
            $this->success('操作失败',U('Admin/Order/delivery_info',array('order_id'=>$data['order_id'])));
        }
    }


    public function delivery_info(){
        $order_id = I('order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        $this->assign('order',$order);
        $this->assign('orderGoods',$orderGoods);
        $delivery_record = M('delivery_doc')->join('LEFT JOIN __SELLER__ ON __SELLER__.seller_id = __DELIVERY_DOC__.admin_id')->where('order_id='.$order_id)->select();
        $this->assign('delivery_record',$delivery_record);//发货记录
        $this->display();
    }

    /**
     * 发货单列表
     */
    public function delivery_list(){
        $this->display();
    }


    /**
     * 改货单列表
     */
    public function return_list(){
        $begin = date('Y-m-d 00:00',(time()-30*60*60*24));//30天前
        $end = date('Y-m-d 23:59',strtotime('+1 days'));
        $this->assign('timegap',$begin.' - '.$end);
        $this->display();
    }
    /*
     * ajax 改货订单列表
     */
    public function ajax_return_list(){
        $orderLogic = new OrderLogic();
        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }

        // 搜索条件
        $condition = array();
        I('consignee') && $condition['_string'] = ' (consignee like "%'.I('consignee').'%")  OR (b.company like "%'.I('consignee').'%") ';
        if($begin && $end){
            $condition['add_time'] = array('between',"$begin,$end");
        }

        $condition['order_prom_type'] = 0;
        I('order_sn') ? $condition['order_sn'] = array('like','%'.trim(I('order_sn')).'%') : false;
        I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
        I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
        I('pay_code') != '' ? $condition['pay_code'] = I('pay_code') : false;
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;
        $condition['a.fenbu_id'] =\session('fenbu_id');


        $condition['is_pint'] = 0;
        $condition['admin_note'] =array('neq','');
        $sort_order = I('order_by','DESC').' '.I('sort');
        $count = M('order a')
            ->join('ty_users b ON a.user_id = b.user_id','LEFT')
            ->where($condition)->count();
        $Page  = new AjaxPage($count,20);

        $show = $Page->show();
        //获取订单列表
        $orderList = $orderLogic->getOrderList($condition,$sort_order,$Page->firstRow,$Page->listRows);
        //获取主订单号

        foreach($orderList as $key=>$value){
            //去重复
            $goods = M('order_goods a')->field('a.*,b.original_img')
                ->join('ty_goods b ON a.goods_id = b.goods_id')
                ->where(array('a.order_id'=>$value['order_id']))
                ->select();
            $orderList[$key]["ruku"]=M('order_jian')->where('order_id='.$value['order_id'].' and '.$this->z.'status_r=1')->count();
            $orderList[$key]["chuku"]=M('order_jian')->where('order_id='.$value['order_id'].' and '.$this->z.'status_c=1')->count();
            $orderList[$key]["biaoqian"]=$orderList[$key]["ruku"]=='0' ? '':'disabled="disabled"';
            foreach ($goods as $keys=>$vs){
                $spec_img = M('spec_image')->where(['spec_image_id'=>$vs['spec_key']])->getField('src');
                if($spec_img){
                    $goods[$keys]['original_img'] = C('MYOSS')['url2'].$spec_img;
                }else{
                    $goods[$keys]['original_img'] =  C('MYOSS')['url2'].$vs['original_img'];
                }
            }
            $orderList[$key]["g_list"]=$goods;

            $orderList[$key]["pay_name"]=M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>$value['pay_code']))->getField('name');

        }

        //echo json_encode($orderList);
        $store_list = M('store')->getField('store_id,store_name');
        $this->assign('store_list',$store_list);
        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }

    /**
     * 删除某个退换货申请
     */
    public function return_del(){
        $id=I('id');
        $order_id=I('order_id');
        if(!empty($id) && !empty($order_id)){
            $returnOrder = M('return_goods')->where("id = $id and order_id=$order_id")->find();
            adminLog('删除了退货单order_id:'.$order_id.'order_sn:'.$returnOrder['order_sn'].'return_order_sn:'.$returnOrder['return_order_sn']);
            M('return_goods')->where("id = $id and order_id=$order_id")->delete();
           
            exit(json_encode([
                'code'=>'200',
                'msg'=>'删除成功！'
            ]));
        }

    }


    /**
     * 删除某个退换货申请
     */
    public function return_cancel(){
        $id=I('id');
        if(!empty($id)){
            M('return_goods')->where("id = $id ")->save(['status'=>3]);
            adminLog('取消了退货单id:'.$id);
            exit(json_encode([
                'code'=>'200',
                'msg'=>'取消成功！'
            ]));
        }

    }

    /**
     * 退款提交银行
     */
    public function return_play(){
        $id=I('id');
        $order_id=I('order_id');
        if(!empty($id) && !empty($order_id)){
            $returnOrder = M('return_goods')->where(['id'=>$id])->find();
            $payModel = new PayController();
            $result = $payModel->returnOrder($returnOrder);
            exit(json_encode($result));
        }

    }
    /**
     * 退换货操作
     */
    public function return_info()
    {
        $id = I('id');
        $return_goods = M('return_goods')->where("id= $id")->find();
        if($return_goods['imgs'])
            $return_goods['imgs'] = explode(',', $return_goods['imgs']);
        $user = M('users')->where("user_id = {$return_goods[user_id]}")->find();
        $goods = M('goods')->where("goods_id = {$return_goods[goods_id]}")->find();
        $type_msg = array('退换','换货');
        $status_msg = array('未处理','处理中','已完成');
        if(IS_POST)
        {
            $data['type'] = I('type');
            $data['status'] = I('status');
            $data['remark'] = I('remark');
            $note ="退换货:{$type_msg[$data['type']]}, 状态:{$status_msg[$data['status']]},处理备注：{$data['remark']}";
            $result = M('return_goods')->where("id= $id")->save($data);
            if($result)
            {
                $type = empty($data['type']) ? 2 : 3;
                $where = " order_id = ".$return_goods['order_id']." and goods_id=".$return_goods['goods_id'];
                M('order_goods')->where($where)->save(array('is_send'=>$type));//更改商品状态
                $orderLogic = new OrderLogic();
                $admin_id = session('admin_id'); // 当前操作的管理员
                $log = $orderLogic->orderActionLog($return_goods[order_id],'refund',$note,$admin_id);
                $this->success('修改成功!');
                exit;
            }
        }

        $this->assign('id',$id); // 用户
        $this->assign('user',$user); // 用户
        $this->assign('goods',$goods);// 商品
        $this->assign('return_goods',$return_goods);// 退换货
        $this->display();
    }

    /**
     * 管理员生成申请退货单
     */
    public function add_return_goods()
    {
        $order_id = I('order_id');
        $goods_id = I('goods_id');

        $return_goods = M('return_goods')->where("order_id = $order_id and goods_id = $goods_id")->find();
        if(!empty($return_goods))
        {
            $this->error('已经提交过退货申请!',U('Admin/Order/return_list'));
            exit;
        }
        $order = M('order')->where("order_id = $order_id")->find();

        $data['order_id'] = $order_id;
        $data['order_sn'] = $order['order_sn'];
        $data['goods_id'] = $goods_id;
        $data['addtime'] = time();
        $data['user_id'] = $order[user_id];
        $data['remark'] = '管理员申请退换货'; // 问题描述
        M('return_goods')->add($data);
        $this->success('申请成功,现在去处理退货',U('Admin/Order/return_list'));
        exit;
    }

    /**
     * 订单操作
     * @param $id
     */
    public function order_action(){
        $orderLogic = new OrderLogic();
        $action = I('get.type');
        $order_id = I('get.order_id');
        if($action && $order_id){
            $a = $orderLogic->orderProcessHandle($order_id,$action);
            $admin_id = session('admin_id'); // 当前操作的管理员
            $res = $orderLogic->orderActionLog($order_id,$action,I('note'),$admin_id);
            if($res && $a){
                exit(json_encode(array('status' => 1,'msg' => '操作成功')));
            }else{
                exit(json_encode(array('status' => 0,'msg' => '操作失败')));
            }
        }else{
            $this->error('参数错误',U('Admin/Order/detail',array('order_id'=>$order_id)));
        }
    }

    public function order_log(){
        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        $condition = array();
        $log =  M('order_action');
        if($begin && $end){
            $condition['log_time'] = array('between',"$begin,$end");
        }
        $admin_id = I('admin_id');
        if($admin_id >0 ){
            $condition['action_user'] = $admin_id;
        }
        $count = $log->where($condition)->count();
        $Page = new \Think\Page($count,20);
        foreach($condition as $key=>$val) {
            $Page->parameter[$key] = urlencode($val);
        }
        $show = $Page->show();
        $list = $log->where($condition)->order('action_id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('list',$list);
        $this->assign('page',$show);
        $admin = M('admin')->getField('admin_id,user_name');
        $this->assign('admin',$admin);
        $this->display();
    }

    /**
     * 检测订单是否可以编辑
     * @param $order
     */
    private function editable($order){
        if($order['shipping_status'] != 0){
            $this->error('已发货订单不允许编辑');
            exit;
        }
        return;
    }


    public function export_order()
    {
        //搜索条件
        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        $order_type=I('order_type');

        // 搜索条件
        $condition = array();
        if($order_type){
            if($order_type=='1'){
                $condition['a.dai_type'] = 0;
            }elseif($order_type=='2'){
                $condition['a.dai_type'] = 1;
            }
        }
        I('biaoshi_xian') ? $condition['b.biaoshi_xian'] = I('biaoshi_xian') : false;
        // I('consignee') && $condition['_string'] = ' (consignee like "%'.I('consignee').'%") OR (b.company like "%'.I('consignee').'%") OR (store_name like "%'.I('consignee').'%") ';
        if($begin && $end){
            $condition['add_time'] = array('between',"$begin,$end");
        }
         if(I('consignee')){
            $condition['a.consignee'] = ['like',I('consignee').'%'];
        }
        if(I('company')){
            $condition['b.company'] = ['like','%'.I('company').'%'];
        }
        if(I('store_name')){
            $condition['c.store_name'] = ['like','%'.I('store_name').'%'];
        }
        if(I('mobile')){
            $condition['b.mobile'] = ['like','%'.I('mobile').'%'];
        }
        $condition['order_prom_type'] = 0;
        I('order_sn') ? $condition['order_sn'] = array('like','%'.trim(I('order_sn')).'%') : false;
        I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
        I('driver') != '' ? $condition['e.nick_name'] = I('driver') : false;
        I('goods_name') ? $condition3['goods_name|goods_id'] = array('like','%'.trim(I('goods_name')).'%') : false;
        I('pda_qdzt') ? $condition['a.pda_qdzt'] = I('pda_qdzt') : false;

        $condition['is_pint'] = 0;
        if(!empty(\session('fenbu_id')))
            $condition['ufenbu_id'] = \session('fenbu_id');


        if($condition3){

            $subQuery2 = M('order_goods')->where($condition3)->getField('order_id',true); //查询订单号

            $duplicates = $subQuery2;
            $duplicates = $duplicates!=[] ? $duplicates : [0];
            $condition['a.order_id'] = ['in',join(',',$duplicates)];
        }

        //获取订单列表
        $orderList = M('order a')
            ->field('a.*,b.company,c.store_name,b.mobile,b.company_address,b.biaoshi_xian,e.nick_name as driver_name')
            ->join('ty_users b ON a.user_id = b.user_id','LEFT')
            ->join('ty_store c ON a.store_id = c.store_id','LEFT')
            ->join('ty_users e ON a.driver_id = e.user_id','LEFT')
            ->order('a.order_id desc')
            ->where($condition)->select();
        //echo \json_encode($orderList);exit;

        $strTable ='<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">商家</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">订单编号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">包装件数</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">线路</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">司机</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货人</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货地址</td>';
        if(session('role_id')==1)
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">电话</td>';

        // $strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">实际支付</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">平台扣点</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">退货金额</td>';
        //$strTable .= '<td style="text-align:center;font-size:12px;" width="*">应收金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">日期</td>';
        $strTable .= '</tr>';


        foreach($orderList as $k=>$val){
            $tuihuo=M('return_goods')->where('order_id='.$val['order_id'])->select();$tuihuos=$tuihuo0=0;
            foreach($tuihuo as $vs){
                $tuihuo0+=\sanwei($vs['member_goods_price']*$vs['goods_num']);
                $tuihuos+=\sanwei($vs['member_goods_price']*$vs['goods_num']-$vs['member_goods_price']*$vs['goods_num']*$vs['points']/100);
            }

            $orderGoods = D('order_goods')->where('order_id='.$val['order_id'])->select();
            $koudian=0;$order_status="";

            if($val['order_status']==0){
                $order_status="<span style='color:red'>未发货</span>";
            }elseif($val['order_status']==1){
                $order_status="<span style='color:blue'>已发货</span>";
            }elseif($val['order_status']==2){
                $order_status="<span style='color:green'>完成</span>";
            }else{
                $order_status="作废/取消";
            }
            foreach($orderGoods as $goods){
                $koudian+=\sanwei($goods['goods_num']*($goods['member_goods_price']*($goods['points']/100)));
            }

            unset($orderGoods);
            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['store_name'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_sn'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['jian_count'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['biaoshi_xian'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['driver_name'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['consignee'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['nickname'].'（'.$val['company'].'）'.$val['company_address'].' </td>';
            if(session('role_id')==1)
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['mobile'].'</td>';

            // $strTable .= '<td style="text-align:left;font-size:12px;">'.($val['goods_price']+$val['yijia']).'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.($val['order_amount']+$val['yijia_heji']).'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$koudian.'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$tuihuo0.'</td>';
            //$strTable .= '<td style="text-align:left;font-size:12px;color:red">'.sanwei($val['order_amount']-$koudian-$tuihuos).'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$order_status.'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.\date('Y-m-d H:i:s',$val['add_time']).' </td>';
            $strTable .= '</tr>';
        }
        $strTable .='</table>';
        unset($orderList);
        downloadExcel($strTable,'order');
        exit();
    }

    /**
     * 商家待结算订单
     * */
    public function export_order_settled()
    {
        $id= I('id');
        $order_sn= I('order_sn');
        $create_date = I('create_date');
        $create_date = str_replace("+"," ",$create_date);
        $create_date2 = $create_date  ? $create_date  : date('Y-m-d',strtotime('-1 month')).' 00:00 - '.date('Y-m-d',strtotime('+1 month')).' 23:59';
        $create_date3 = explode(' - ',$create_date2);
        $create_date4=($create_date3[0]==$create_date3[1]) ? strtotime($create_date3[1])+86399 :strtotime($create_date3[1]);

        $where = "a.store_id = ".session('store_id')." and (d.withdrawals_id=0 or d.withdrawals_id is null) and c.status_r=1 and c.ruku_time >= '".strtotime($create_date3[0])."' and c.ruku_time <= '".$create_date4."' ";
        if($order_sn){
            $where .= " and a.order_sn like '%".$order_sn."%'";
        }

        $count = M()->query("SELECT a.order_id,a.order_sn,a.order_status,a.order_amount,a.coupon_price,a.dai_type,
		(SELECT sum(b.goods_num*b.member_goods_price*b.points/100) from ty_order_goods b where b.order_id=a.order_id) as commis_totals,
		(SELECT (a.order_amount*b.points/100) from ty_order_goods b where b.order_id=a.order_id limit 1) as commis_totals_k,
		c.status_r,c.ruku_time,d.order_totals
		 from ty_order a 
		 INNER JOIN ty_order_jian c on a.order_id=c.order_id 
		 LEFT JOIN ty_order_statis d on a.order_sn=d.order_sn 
		 where $where group by a.order_sn");

        //计算合计金额
        $dan_heji=$kou_heji=$yin_heji=$shi_heji=0;
        foreach($count as $v){

            if($v['dai_type']==2){
                $kou_heji+=$v['commis_totals_k']; //$dan_heji+=0;
            }else{
                $kou_heji+=$v['commis_totals']; //
            }

            if($v['order_totals'] && $v['order_amount']!=$v['order_totals'])
                $shi_heji+=$v['order_totals'];
            else
                $shi_heji+=$v['order_amount']+$v['coupon_price'];

            $dan_heji+=$v['order_amount']+$v['coupon_price'];
        }

        $yin_heji=$shi_heji-$kou_heji;

        $list = M()->query("SELECT a.change,a.order_id,a.admin_note,a.order_sn,a.order_status,a.order_amount,a.coupon_price,a.dai_type,
		(SELECT sum(b.goods_num*b.member_goods_price*b.points/100) from ty_order_goods b where b.order_id=a.order_id) as commis_totals,
		(SELECT (a.order_amount*b.points/100) from ty_order_goods b where b.order_id=a.order_id limit 1) as commis_totals_k,
		c.status_r,c.ruku_time,d.order_totals
		 from ty_order a 
		 INNER JOIN ty_order_jian c on a.order_id=c.order_id 
		 LEFT JOIN ty_order_statis d on a.order_sn=d.order_sn 
		 where $where group by a.order_sn ORDER BY a.order_id desc");

        $order_status = C('ORDER_STATUS');
        $strTable ='<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">ID</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">单号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">订单金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">平台收款</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">平台扣点</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">抹零金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">应收金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">平台备注</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">入库时间</td>';
        $strTable .= '</tr>';
        foreach($list as $key=>$v){
            $list[$key]['order_amount'] = $v['order_amount'] + $v['coupon_price'];
            $list[$key]['commis_totals']=$v['dai_type']==2 ? $v['commis_totals_k'] : $v['commis_totals'];

            if($v['order_totals'] && $v['order_amount']!=$v['order_totals']){
                $list[$key]['yingshou']=$v['order_totals']-$list[$key]['commis_totals'];
            }else{
                $list[$key]['yingshou']=$v['order_amount']-$v['commis_totals'];
                $list[$key]['order_totals']=$v['order_amount']+ $v['coupon_price'];
            }

            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">&nbsp;'.$v['order_id'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">&nbsp;'.$v['order_sn'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">&nbsp;'.$v['order_amount'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">&nbsp;'.sanwei($list[$key]['order_totals']).'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">&nbsp;'.sanwei($v['commis_totals']).'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">&nbsp;'.$v['change'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">&nbsp;'.sanwei($list[$key]['yingshou']).'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">&nbsp;'.$order_status[$v['order_status']].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">&nbsp;'.$v['admin_note'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">&nbsp;'.date('Y-m-d h:i:s',$v['ruku_time']).'</td>';
            $strTable .= '</tr>';
        }

        $strTable .='</table>';
        unset($list);
        downloadExcel($strTable,'order');
        exit();
    }

    public function export_order_gai()
    {
        $orderLogic = new OrderLogic();
        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }

        // 搜索条件
        $condition = array();
        I('consignee') && $condition['_string'] = ' (consignee like "%'.I('consignee').'%")  OR (company like "%'.I('consignee').'%") ';
        if($begin && $end){
            $condition['add_time'] = array('between',"$begin,$end");
        }

        $condition['order_prom_type'] = 0;
        I('order_sn') ? $condition['order_sn'] = array('like','%'.trim(I('order_sn')).'%') : false;
        I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
        I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
        I('pay_code') != '' ? $condition['pay_code'] = I('pay_code') : false;
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;


        $condition['is_pint'] = 0;
        $condition['admin_note'] =array('neq','');
        $condition['master_order_sn'] = ['neq',''];
        $sort_order = I('order_by','DESC').' '.I('sort');

        $orderList = M('order a')
            ->field('a.*,b.company,c.store_name,b.mobile,b.company_address')
            ->join('ty_users b ON a.user_id = b.user_id','LEFT')
            ->join('ty_store c ON a.store_id = c.store_id','LEFT')
            ->where($condition)->order($sort_order)->select();
        //获取主订单号

        $strTable ='<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">商家</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">订单编号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">包装件数</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货人</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货地址</td>';
        //$strTable .= '<td style="text-align:center;font-size:12px;" width="*">电话</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">实际支付</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">平台扣点</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">应收金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">平台改单</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">日期</td>';
        $strTable .= '</tr>';


        foreach($orderList as $k=>$val){

            $orderGoods = D('order_goods')->where('order_id='.$val['order_id'])->select();
            $koudian=0;$order_status="";

            if($val['order_status']==0){
                $order_status="<span style='color:red'>未发货</span>";
            }elseif($val['order_status']==1){
                $order_status="<span style='color:blue'>已发货</span>";
            }elseif($val['order_status']==2){
                $order_status="<span style='color:green'>完成</span>";
            }else{
                $order_status="作废/取消";
            }
            foreach($orderGoods as $goods){
                $koudian+=\sanwei($goods['member_goods_price']*$goods['goods_num']*$goods['points']/100);
            }

            unset($orderGoods);
            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['store_name'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_sn'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['jian_count'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['consignee'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['nickname'].'（'.$val['company'].'）'.$val['company_address'].' </td>';
            //$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['mobile'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['goods_price'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['order_amount'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$koudian.'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;color:red">'.($val['order_amount']-$koudian).'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$order_status.'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['admin_note'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.\date('Y-m-d H:i:s',$val['add_time']).' </td>';
            $strTable .= '</tr>';
        }
        $strTable .='</table>';
        unset($orderList);
        downloadExcel($strTable,'order');
        exit();
    }

    /**
     * 添加一笔订单
     */
    public function add_order()
    {
        $order = array();
        //  获取省份
        $province = M('region')->where(array('parent_id'=>0,'level'=>1))->select();
        //  获取订单城市
        $city =  M('region')->where(array('parent_id'=>$order['province'],'level'=>2))->select();
        //  获取订单地区
        $area =  M('region')->where(array('parent_id'=>$order['city'],'level'=>3))->select();
        //  获取配送方式
        $shipping_list = M('plugin')->where(array('status'=>1,'type'=>'shipping'))->select();
        //  获取支付方式
        $payment_list = M('plugin')->where(array('status'=>1,'type'=>'payment'))->select();
        if(IS_POST)
        {
            $order['user_id'] = I('user_id');// 用户id 可以为空
            $order['consignee'] = I('consignee');// 收货人
            $order['province'] = I('province'); // 省份
            $order['city'] = I('city'); // 城市
            $order['district'] = I('district'); // 县
            $order['address'] = I('address'); // 收货地址
            $order['mobile'] = I('mobile'); // 手机
            $order['invoice_title'] = I('invoice_title');// 发票
            $order['admin_note'] = I('admin_note'); // 管理员备注
            $order['order_sn'] = date('YmdHis').mt_rand(1000,9999); // 订单编号;
            $order['add_time'] = time(); //
            $order['shipping_code'] = I('shipping');// 物流方式
            $order['shipping_name'] = M('plugin')->where(array('status'=>1,'type'=>'shipping','code'=>I('shipping')))->getField('name');
            $order['pay_code'] = I('payment');// 支付方式
            $order['pay_name'] = M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>I('payment')))->getField('name');

            $goods_id_arr = I("goods_id");
            $orderLogic = new OrderLogic();
            $order_goods = $orderLogic->get_spec_goods($goods_id_arr);
            $result = calculate_price($order['user_id'],$order_goods,$order['shipping_code'],0,$order[province],$order[city],$order[district],0,0,0,0,0,11);
            if($result['status'] < 0)
            {
                $this->error($result['msg']);
            }

            $order['goods_price']    = $result['result']['goods_price']; // 商品总价
            $order['shipping_price'] = $result['result']['shipping_price']; //物流费
            $order['order_amount']   = $result['result']['order_amount']; // 应付金额
            $order['total_amount']   = $result['result']['total_amount']; // 订单总价

            // 添加订单
            $order_id = M('order')->add($order);
            if($order_id)
            {
                foreach($order_goods as $key => $val)
                {
                    $val['order_id'] = $order_id;
                    $rec_id = M('order_goods')->add($val);
                    if(!$rec_id)
                        $this->error('添加失败');
                }
                $this->success('添加商品成功',U("Admin/Order/detail",array('order_id'=>$order_id)));
                exit();
            }
            else{
                $this->error('添加失败');
            }
        }
        $this->assign('shipping_list',$shipping_list);
        $this->assign('payment_list',$payment_list);
        $this->assign('province',$province);
        $this->assign('city',$city);
        $this->assign('area',$area);
        $this->display();
    }

    /**
     * 选择搜索商品
     */
    public function search_goods()
    {
        $brandList =  M("brand")->select();
        $categoryList =  M("goods_category")->select();
        $this->assign('categoryList',$categoryList);
        $this->assign('brandList',$brandList);
        $where = ' is_on_sale = 1 ';//搜索条件
        I('intro')  && $where = "$where and ".I('intro')." = 1";
        if(I('cat_id')){
            $this->assign('cat_id',I('cat_id'));
            $grandson_ids = getCatGrandson(I('cat_id'));
            $where = " $where  and cat_id in(".  implode(',', $grandson_ids).") "; // 初始化搜索条件

        }
        if(I('brand_id')){
            $this->assign('brand_id',I('brand_id'));
            $where = "$where and brand_id = ".I('brand_id');
        }
        if(!empty($_REQUEST['keywords']))
        {
            $this->assign('keywords',I('keywords'));
            $where = "$where and (goods_name like '%".I('keywords')."%' or keywords like '%".I('keywords')."%')" ;
        }
        $goodsList = M('goods')->where($where)->order('goods_id DESC')->limit(10)->select();

        foreach($goodsList as $key => $val)
        {
            $spec_goods = M('spec_goods_price')->where("goods_id = {$val['goods_id']}")->select();
            $goodsList[$key]['spec_goods'] = $spec_goods;
        }
        $this->assign('goodsList',$goodsList);
        $this->display();
    }

    public function ajaxOrderNotice(){
        $order_amount = M('order')->where(array('order_status'=>0))->count();
        echo $order_amount;
    }


    /*
     *订单退货首页
     */
    public function tuihuo_list(){
        $action=I('action');$datas=I('datas');
        if($action=='yes' && !empty($datas)){
            $check_time = I('check_time');
            $datas=\explode(',',$datas);
            foreach($datas as $v){
                M('return_goods')->where(['id'=>$v,'withdrawals_id'=>0])->save(['status'=>1,'check_time'=>$check_time]);
            }
            echo 1;
            exit;
        }elseif($action=='quhuo' && !empty($datas)){
            $datas=\explode(',',$datas);
            foreach($datas as $v){
                M('return_goods')->where(['id'=>$v])->save(['getorder'=>1,'getorder_time'=>date("Y-m-d H:i:s",time())]);
            }
            echo 1;
            exit;
        }elseif($action=='ruku' && !empty($datas)){
            $datas=\explode(',',$datas);
            foreach($datas as $v){
                M('return_goods')->where(['id'=>$v,'getorder'=>2])->save(['getorder'=>0,'ruku_time'=>time()]);
            }
            
            echo 1;
            exit;
        }elseif($action=="dayin"){
			M('return_goods')->where('id in('.I('ids').')')->setInc('print_num');
			exit;
		}

        $orderLogic = new OrderLogic();
        $pda_open=tpCache("basic")['pda_open'];
        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }else{
            $lastweek = strtotime("-3 day");
            $begin = $lastweek;
            $end =  time();
        }

        $timegap2 = I('timegap2');
        if($timegap2){
            $gap2 = explode(' - ', $timegap2);
            $begin2 = $gap2[0];
            $end2 = $gap2[1];
        }
//        else{
//            $lastweek2 = date('Y-m-d H:i',strtotime("-3 day"));
//            $begin2 = $lastweek2;
//            $end2 =  date('Y-m-d H:i',time());
//        }

        $this->assign('timegap',date('Y-m-d H:i',$begin).' - '.date('Y-m-d H:i',$end));
        //$this->assign('timegap2',$begin2.' - '.$end2);

        // 搜索条件
        $condition = array();
        if($begin && $end){
            $condition['tuihuo_time'] = array('between',"$begin,$end");
        }

        if($begin2 && $end2){
            $condition['getorder_time'] = array('between',"$begin2,$end2");
        }
        if(I('fenbu_id')!==""){
            I('fenbu_id')!=0 ? $condition['b.fenbu_id'] = I('fenbu_id') : $condition['b.fenbu_id'] = \session('fenbu_id');
        }
        
//		session('fenbu_id')==0 ? $condition['d.fenbu_id'] = session('fenbu_id') : false;
        I('status')!="" ? $condition['status'] = I('status') : false;
        I('getorder')!="" ? $condition['getorder'] = I('getorder') : false;
        I('id')!="" ? $condition['id'] = I('id') : false;
        I('driver') ? $condition['f.nick_name'] = array('like','%'.trim(I('driver')).'%') : false;
        I('order_sn') && $condition['_string'] = ' (remark like "%'.I('order_sn').'%")  OR (a.order_sn like "%'.I('order_sn').'%") ';
        I('consignee') && $condition['_string'] = ' (b.nickname like "%'.I('consignee').'%")  OR (b.company like "%'.I('consignee').'%") ';
        I('store') ? $condition['d.store_name'] = array('like','%'.trim(I('store')).'%') : false;
        // I('print_num')!= ? $condition['a.print_num'] = array('gt',0) : false;

        if(I('print_num') !== ''){
            $condition['a.print_num']=I('print_num')!= 0 ? ['gt',0] : 0;
        }

        $count = M('return_goods a')
            ->field('(a.member_goods_price+a.yijia) member_goods_price,a.yijia,a.goods_num,a.points,a.order_sn')
            ->join('ty_users b ON a.user_id = b.user_id','LEFT')
            ->join('ty_store d ON a.store_id = d.store_id','LEFT')
            ->join('ty_users f ON a.driver_id = f.user_id','LEFT')
            ->where($condition)->select();

        foreach($count as $v){
            $dsprice=(float)($v['member_goods_price'])*(float)$v['goods_num']; //订单价
            $ptprice=($dsprice-$v['yijia'])*($v['points']/100); //平台价
            $ptprices=$dsprice-$ptprice;

            $heji_price+=$dsprice;
            $heji_ptprice+=$ptprice;
            $heji_ptprices+=$ptprices;
        }
        //合计金额

        $Page  = new Page(\count($count),100);
        //  搜索条件下 分页赋值

        $show = $Page->show();
        //获取订单列表
        $orderList = M('return_goods a')
            ->field('a.*,(a.member_goods_price+a.yijia) member_goods_price,b.*,c.original_img as imgs,c.goods_name,d.store_name,e.pay_no,e.pay_status as order_pay_status,f.nick_name,g.fenbu_name,h.key_name')
            ->join('ty_users b ON a.user_id = b.user_id','LEFT')
            ->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
            ->join('ty_store d ON a.store_id = d.store_id','LEFT')
            ->join('ty_order e ON a.order_id = e.order_id','LEFT')
            ->join('ty_users f ON a.driver_id = f.user_id','LEFT')
            ->join('ty_fenbu g ON e.ufenbu_id = g.fenbu_id','LEFT')
            ->join('ty_spec_goods_price h ON a.spec_key=h.key','LEFT')
            ->where($condition)->limit("$Page->firstRow,$Page->listRows")->order('a.id desc')->select();
        foreach ($orderList as $k=>$v){
            if(empty($orderList[$k]['ruku_time'])){
                $orderList[$k]['ruku_time'] = '没有退货入库';
            }else{
                $orderList[$k]['ruku_time'] = date('Y-d-m H:i:s',$orderList[$k]['ruku_time']);
            }
        }
		$this->assign('drivers',M('users')->where('is_driver=1 and is_lock=0')->select());
        //echo json_encode($orderList);exit;
        $store_list = M('store')->getField('store_id,store_name');
        $this->assign('store_list',$store_list);
        $this->assign('orderList',$orderList);
        $this->assign('fenbu_list',$this->fenbu_list);
        $this->assign('heji_ptprice',sanwei($heji_ptprice));
        $this->assign('heji_ptprices',sanwei($heji_ptprices));
        $this->assign('heji_price',sanwei($heji_price));
        $this->assign('pda_open',$pda_open);
        $this->assign('role_id',session('role_id'));
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('check_time',date('Y-m-d',time()));
        $this->display();
    }

/**
**单个审核退货单
**/
    public function orderExamine(){
        $check_time = I('check_time');
        $Id = I('id');
       
        M('return_goods')->where(['id'=>$Id])->save(['status'=>1,'check_time'=>$check_time]);
        $retungoods = M('return_goods')->where(['id'=>$Id])->find();
        $returnPrice = $retungoods['goods_num']*$retungoods['member_goods_price'];
        M('users_price')->where('order_id='.$retungoods['order_id'])->setDec('price',$returnPrice);
        adminLog('审核了退货单id'.$Id);
         echo 1;
         exit;
    }


    /*
 *订单退货首页
 */
    public function tuihuo_list2(){
        $action=I('action');
        $datas=I('datas');
    //   dump($datas);
        $returnGoodsArray = '';
        if(!empty($datas)){
            $datas=\explode(',',$datas);
            // dump($datas);
            foreach ($datas as $k=>$v){
                 $return_goods = M('return_goods')->where(['return_order_sn'=>$v])->select();
                 foreach ($return_goods as  $key=>$val){
                     $return_goodsTwo = M('return_goods')->field('id,status')->where(['id'=>$val['id']])->find();
                    //  if($return_goodsTwo['status'] != 3){
                        $returnGoodsArray .= $val['id'].',';
                    //  }
                 }
                 
            }
            // dump($datas);
            // sort($returnGoodsArray);
            $datas = substr($returnGoodsArray,0,-1);
            // dump($datas);
            $datas=\explode(',',$datas);
            // dump($datas);
        }
    //   dump($datas);
    //   die;
        if($action=='yes' && !empty($datas)){
            $check_time = I('check_time');
         
            // $datas=\explode(',',$datas);
            foreach($datas as $v){
                $retungoods = M('return_goods')->where(['id'=>$v,'withdrawals_id'=>0])->find();
                M('return_goods')->where(['id'=>$v,'withdrawals_id'=>0])->save(['status'=>1,'check_time'=>$check_time]);
                $userOrder = M('order o')->field('u.pay_points,u.user_id')->join('ty_users u on u.user_id=o.user_id','LEFT')->where(['order_id'=>$retungoods['order_id']])->find();
                if(!empty($userOrder)){
                    $returnPrice = $retungoods['goods_num']*$retungoods['member_goods_price'];
                    if(($userOrder['pay_points'] - $returnPrice) > 0){
                        M('users')->where(['user_id'=>$userOrder['user_id']])->setDec('pay_points',$returnPrice);
                    }else{
                        M('users')->where(['user_id'=>$userOrder['user_id']])->save(['pay_points'=>0]);
                    }
                    M('users_price')->where('order_id='.$retungoods['order_id'])->setDec('price',$returnPrice);
                    // accountLog($list['user_id'],0,$list['order_amount'],'订单 '.$list['order_sn'].' 赠送的积分！',0,$list['order_id']);
                }
            }
            
            echo 1;
            exit;
        }elseif($action=='quhuo' && !empty($datas)){
            // $datas=\explode(',',$datas);
            foreach($datas as $v){
                M('return_goods')->where(['id'=>$v])->save(['getorder'=>1,'getorder_time'=>date("Y-m-d H:i:s",time())]);
            }
            echo 1;
            exit;
        }elseif($action=='del' && !empty($datas)){
            // $datas=\explode(',',$datas);
          
            foreach($datas as $v){
                $retungoods = M('return_goods')->where('id='.$v.' and status != 1')->delete();
                // M('return_goods')->where(['id'=>$v])->save(['status'=>3]);
                // if($retungoods['status'] == 1){
                //     $userOrder = M('order o')->field('u.pay_points,u.user_id')->join('ty_users u on u.user_id=o.user_id','LEFT')->where(['order_id'=>$retungoods['order_id']])->find();
                //     $returnPrice = $retungoods['goods_num']*$retungoods['member_goods_price'];
                //     M('users')->where(['user_id'=>$userOrder['user_id']])->setInc('pay_points',$returnPrice);
                // }
                adminLog('单号：'.$v.'删除退货');
            }
            echo 1;
            exit;
        }elseif($action=='cancel' && !empty($datas)){
            // $datas=\explode(',',$datas);
            foreach($datas as $v){
                $retungoods = M('return_goods')->where(['id'=>$v])->find();
                M('return_goods')->where(['id'=>$v])->save(['status'=>3]);
                if($retungoods['status'] == 1){
                    $userOrder = M('order o')->field('u.pay_points,u.user_id')->join('ty_users u on u.user_id=o.user_id','LEFT')->where(['order_id'=>$retungoods['order_id']])->find();
                    $returnPrice = $retungoods['goods_num']*$retungoods['member_goods_price'];
                    M('users')->where(['user_id'=>$userOrder['user_id']])->setInc('pay_points',$returnPrice);
                }
                adminLog('单号：'.$v.'取消退货');
            }
            echo 1;
            exit;
        }elseif($action=='ruku' && !empty($datas)){
            // $datas=\explode(',',$datas);
            foreach($datas as $v){
                M('return_goods')->where(['id'=>$v,'getorder'=>2])->save(['getorder'=>0,'ruku_time'=>time()]);
            }
            echo 1;
            exit;
        }elseif($action=="dayin"){
            M('return_goods')->where('return_order_sn in('.I('ids').')')->setInc('print_num');
            exit;
        }

        $orderLogic = new OrderLogic();
        $pda_open=tpCache("basic")['pda_open'];
        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }else{
            $lastweek = strtotime("-3 day");
            $newtime = date('Y-m-d', $lastweek);
            $begin = strtotime($newtime);
            // $end =  time();
            
            $currentDate = date('Y-m-d', time());
            // 获取当前0点时间戳
            $new = strtotime($currentDate);
            $end = $new+86399;
        }

        $timegap2 = I('timegap2');
        if($timegap2){
            $gap2 = explode(' - ', $timegap2);
            $begin2 = $gap2[0];
            $end2 = $gap2[1];
        }
//        else{
//            $lastweek2 = date('Y-m-d H:i',strtotime("-3 day"));
//            $begin2 = $lastweek2;
//            $end2 =  date('Y-m-d H:i',time());
//        }

        
        $this->assign('timegap',date('Y-m-d H:i',$begin).' - '.date('Y-m-d H:i',$end));
        // $this->assign('timegap2',date('Y-m-d H:i',$begin2).' - '.date('Y-m-d H:i',$end2));
        //$this->assign('timegap2',$begin2.' - '.$end2);

        // 搜索条件
        $condition = array();
        if($begin && $end){
            $condition['tuihuo_time'] = array('between',"$begin,$end");
        }
        
        if($begin2 && $end2){
            $condition['getorder_time'] = array('between',[$begin2,$end2]);
        }
        if(I('fenbu_id')!==""){
            I('fenbu_id')!=0 ? $condition['b.fenbu_id'] = I('fenbu_id') : $condition['b.fenbu_id'] = \session('fenbu_id');
        }

//		session('fenbu_id')==0 ? $condition['d.fenbu_id'] = session('fenbu_id') : false;
        I('status')!="" ? $condition['status'] = I('status') : false;
        I('biaoshi_xian')!="" ? $condition['b.biaoshi_xian'] = I('biaoshi_xian') : false;
        I('getorder')!="" ? $condition['getorder'] = I('getorder') : false;
        I('goods_name') ? $condition['goods_name'] = array('like','%'.trim(I('goods_name')).'%') : false;
        I('driver') ? $condition['f.nick_name'] = array('like','%'.trim(I('driver')).'%') : false;
        
        I('consignee') && $condition['_string'] = ' (b.nickname like "%'.I('consignee').'%")  OR (b.company like "%'.I('consignee').'%") ';
        I('store') ? $condition['d.store_name'] = array('like','%'.trim(I('store')).'%') : false;
        // I('print_num')!= ? $condition['a.print_num'] = array('gt',0) : false;
        // I('return_order_sn')!="" ? $condition['return_order_sn'] = ['like','%'.I('return_order_sn').'%'] : false;
        $order_sn = I('order_sn');
        if(!empty($order_sn)){
            $condition['_string'] = ' (remark like "%'.I('order_sn').'%")  OR (a.order_sn like "%'.I('order_sn').'%") OR (a.return_order_sn like "%'.I('order_sn').'%")';
            // $condition['return_order_sn'] = ['like','%'.I('return_order_sn').'%'];
            
        }
         if(!empty(session('fenbu_id'))){
            $condition['b.fenbu_id']=session('fenbu_id');
        }
        if(I('print_num') !== ''){
            $condition['a.print_num']=I('print_num')!= 0 ? ['gt',0] : 0;
        }
        // dump($condition);
        $count = M('return_goods a')
            ->field('a.id,a.order_id,o.coupon_price,o.total_amount,a.return_order_sn,SUM(((a.member_goods_price+a.yijia)*a.goods_num)) as sum,a.yijia')
            // ->field('a.*')
            ->join('ty_goods g ON g.goods_id = a.goods_id','LEFT')
            ->join('ty_users b ON a.user_id = b.user_id','LEFT')
            ->join('ty_store d ON a.store_id = d.store_id','LEFT')
            ->join('ty_users f ON a.driver_id = f.user_id','LEFT')
            ->join('ty_order o ON a.order_id = o.order_id','LEFT')
            ->where($condition)
            ->group('a.return_order_sn')
            ->select();
        //   dump(count($count));
        $priceheji = $conpu_price= 0;
        foreach ($count as $k=>$v){
            $where = [];
            $where['addtime'] = array('between',"$begin,$end");
            $where['order_id'] = $v['order_id'];
            // $coupom_order = M('order')->where(['order_id'=>$v['order_id']])->getField('coupon_price');
            // $coupom_total_amount = M('order')->where(['order_id'=>$v['order_id']])->getField('total_amount');
            $coupom_order = $v['coupon_price'];
            // dump($coupom_order);
            $coupom_total_amount = $v['total_amount'];
            $return_goods = M('return_goods')->where($where)->select();
            // dump($return_goods);
            $couponreturngoods = 0;
            foreach ($return_goods as $key=>$val){
                if($coupom_order > 0){
                    $Proportion = (($val['member_goods_price']+$val['yijia']) * $val['goods_num'])/$coupom_total_amount;
                    //算出优惠金额
                    $couponreturngoods += geshi($Proportion*$coupom_order);
                }else{
                    $couponreturngoods = 0;
                }
                // dump($Proportion);
                // dump($couponreturngoods);
            }
        // dump($couponreturngoods);
            $priceheji +=$v['sum'];
            $conpu_price +=$couponreturngoods;
        }
        // dump($priceheji);
        $Page  = new Page2(count($count),100);

        //  搜索条件下 分页赋值

        $show = $Page->show();

        $orderList = M('return_goods a')
            ->field('SUM(((a.member_goods_price+a.yijia)*a.goods_num)) as sum,a.return_order_sn,d.store_name,f.nick_name as nickname,b.company,a.status,a.order_id')
            ->join('ty_users b ON a.user_id = b.user_id','LEFT')
            ->join('ty_goods g ON g.goods_id = a.goods_id','LEFT')
            ->join('ty_store d ON a.store_id = d.store_id','LEFT')
            ->join('ty_users f ON a.driver_id = f.user_id','LEFT')
            ->where($condition)
            ->group('a.return_order_sn')
            ->limit("$Page->firstRow,$Page->listRows")->order('a.id desc')
            ->select(); //主订单号
          
        //获取订单列表
        foreach ($orderList as $kk=>$item){
            // dump($item);
            $order_list = M('return_goods a')
                ->field('a.*,(a.member_goods_price+a.yijia) member_goods_price,b.*,c.original_img as imgs,c.goods_name,d.store_name,e.pay_no,e.pay_status as order_pay_status,f.nick_name,g.fenbu_name,h.key_name,e.total_amount')
                ->join('ty_users b ON a.user_id = b.user_id','LEFT')
                ->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
                ->join('ty_store d ON a.store_id = d.store_id','LEFT')
                ->join('ty_order e ON a.order_id = e.order_id','LEFT')
                ->join('ty_users f ON a.driver_id = f.user_id','LEFT')
                ->join('ty_fenbu g ON b.fenbu_id = g.fenbu_id','LEFT')
                ->join('ty_spec_goods_price h ON a.spec_key=h.key','LEFT')
                ->where(['a.return_order_sn'=>$item['return_order_sn']])->order('a.id desc')->group('a.spec_key')->select();
                
            $coupon_price = M('order')->where(['order_id'=>$item['order_id']])->getField('coupon_price');
            if(!empty($coupon_price)){
                $orderList[$kk]['coupon_price'] = $coupon_price; 
            }else{
                $orderList[$kk]['coupon_price'] = 0;
            }
            $order_list_coupon = 0;
            foreach ($order_list as $k=>$v){
               
                 if($orderList[$kk]['coupon_price']>0){
                         //算出这个退货单在这里占多少
                        $Proportion = ($v['member_goods_price'] * $v['goods_num'])/$v['total_amount'];
                      
                        //算出优惠金额
                        $order_list[$k]['coupon_price'] = geshi($Proportion*$coupon_price);
                    }else{
                        $order_list[$k]['coupon_price'] = 0;
                    }
                
                if(empty($order_list[$k]['ruku_time'])){
                    $order_list[$k]['ruku_time'] = '没有退货入库';
                }else{
                    $order_list[$k]['ruku_time'] = date('Y-m-d H:i:s',$order_list[$k]['ruku_time']);
                }
                // dump($order_list[$k]['coupon_price']);
                $order_list_coupon += $order_list[$k]['coupon_price'];
            }
            $orderList[$kk]['order_list'] = $order_list;
            $orderList[$kk]['order_list_coupon'] = $order_list_coupon;
        }
        // dump($orderList);
        
            
       
        // dump($orderList);
        $this->assign('drivers',M('users')->where('is_driver=1 and is_lock=0')->select());
        //echo json_encode($orderList);exit;
        $store_list = M('store')->getField('store_id,store_name');
        $this->assign('store_list',$store_list);
        $this->assign('orderList',$orderList);
        $this->assign('fenbu_list',$this->fenbu_list);
        $this->assign('pda_open',$pda_open);
        $this->assign('priceheji',$priceheji);
        $this->assign('conpu_price',$conpu_price);
        $this->assign('role_id',session('role_id'));
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('check_time',date('Y-m-d',time()));
        $this->display();
    }




  


    public function tuihuo_goods(){
        $order_id=I('order_id',0);
        $list=M('order_goods a')->field('a.*')->where('order_id='.$order_id)->select();

        $neirong='';
        foreach($list as $v){
            $spec=M('spec_goods_price')->where('`key`="'.$v['spec_key'].'"')->getField('key_name');
            $return_num = M('return_goods')->where(['order_id'=>$order_id,'goods_id'=>$v['goods_id'],'spec_key'=>$v['spec_key'],'status'=>['neq',3]])->sum('goods_num');
            $v['goods_num'] = $v['goods_num']-$return_num;
            $neirong.='<tr>
							<td class="text-left">'.$v['goods_name'].'（'.$spec.'）</td>
							<td class="text-left">'.$v['member_goods_price'].'</td>
							<td class="text-left">'.$v['points'].'</td>
							<td class="text-left">
							<input type="hidden" name="goods_ids[]" value="'.$v['goods_id'].'">
							<input type="hidden" name="keys[]" value="'.$v['spec_key'].'">
							<input type="hidden" name="prices[]" value="'.$v['member_goods_price'].'">
							<input type="hidden" name="pointss[]" value="'.$v['points'].'">
							<input type="text" class="input-sm" onchange="javascript: $(this).parent().next().html(($(this).val() * '.$v['member_goods_price'].').toFixed(3))" name="goods_nums[]" value="'.$v['goods_num'].'"></td>
							<td class="text-left goods_price">'.($v['member_goods_price']+$v['yijia']) * $v['goods_num'].'</td>
							<td class="text-left">
							<input type="text" class="input-sm" name="reasons[]" value="">
							<td><a href="javascript:void(0)" onclick="javascript:$(this).parent().parent().remove();">删除</a></td>
                            </td>
							</tr>';
        }

        echo $neirong;
    }

  public function tuihuo_keys(){
        $key=trim(I('key'));
        $shangjia=trim(I('shangjia'));
		$kehu=trim(I('kehu'));
		$chanpin=trim(I('chanpin'));
		$order_sn=trim(I('order_sn'));
		$biaoshi_xian=trim(I('biaoshi_xian'));
		$action=I('action');
        if($action=="user"){
            if($kehu){
                $user_id=M('users')->where('company like "%'.$kehu.'%"')->getField('user_id',true);
                if(!empty($user_id)){
                    $user_id=join(",",$user_id);
                }
                
                if($biaoshi_xian){
                    $user_id=M('users')->where('biaoshi_xian = "'.$biaoshi_xian.'" and user_id in ('.$user_id.') ')->getField('user_id',true);
                    if(!empty($user_id)){
                        $user_id=join(",",$user_id);
                    }
                    
                }

                if($shangjia)
                    $store_id=M('store')->where('store_name like "%'.$shangjia.'%"')->getField('store_id');

                $order_sn=empty($order_sn) ? '2': $order_sn;

                $where=empty($store_id) ? ' a.order_sn like "%'.$order_sn.'%" and a.user_id in('.$user_id.') and a.order_status in(1,2) ' : ' a.order_sn like "%'.$order_sn.'%" and b.store_id='.$store_id.' and a.user_id in('.$user_id.') and a.order_status in(1,2) ';

            }else{
                $where= ' a.order_sn = "'.$order_sn.'" and a.order_status in(1,2) ';
            }
            // dump($where);die;
            if(empty($chanpin)){
    			$list=M('order a')
    			->field('a.*,b.store_name,e.nick_name as driver_name')
    			->join('ty_store b on a.store_id=b.store_id')
    			->join('ty_users e on a.driver_id=e.user_id','left')
    			->where($where)->limit(10)->select();
    // 			dump($list);
    			$neirong='';
    			foreach($list as $v){
    				$neirong.='<li ref="'.$v['driver_name'].'" req="'.$v['driver_id'].'"  rel="'.$v['store_id'].'" rev="'.$v['user_id'].'" alt="'.$v['store_name'].'" title="'.$v['consignee'].'" id="'.$v['order_id'].'">'.$v['order_sn'].'</li>';
			    }
            }else{
                $goods_list=M('order_goods a')
				->field('a.order_id')
				->join('ty_order b on a.order_id=b.order_id')
				->where('a.goods_name like "%'.$chanpin.'%" and b.user_id='.$user_id)
				->group('a.order_id')
				->select();print_r($goods_list);
				$goods_list=join(",",$arr);
				echo 'a.order_id in('.$goods_list.') and '.$where;
                
               $list=M('order a')
                ->field('a.*,b.store_name,e.nick_name as driver_name')
                ->join('ty_store b on a.store_id=b.store_id')
                ->join('ty_users e on a.driver_id=e.user_id','left')
                ->where('a.order_sn like "%'.$key.'%" and order_status in(0,1,2) and a.driver_id != 0')->order('a.order_id desc')->limit(10)->select();
                $neirong='';
                foreach($list as $v){
                    $neirong.='<li ref="'.$v['driver_name'].'" req="'.$v['driver_id'].'" rel="'.$v['store_id'].'" rev="'.$v['user_id'].'" alt="'.$v['store_name'].'" title="'.$v['consignee'].'" id="'.$v['order_id'].'">'.$v['order_sn'].'</li>';
                } 
            }
            // dump($neirong);
            
        }else if($action=='driver'){
            $list = M('users')->where(['nick_name|nickname|mobile'=>['like','%'.$key.'%'],'is_driver'=>1])->select();
            $neirong='';
            foreach($list as $v){
                $neirong.='<li ref="'.$v['nick_name'].'" req="'.$v['user_id'].'" alt="'.$v['nick_name'].'" title="'.$v['nick_name'].'" id="'.$v['user_id'].'">'.$v['nick_name'].'|'.$v['nickname'].'</li>';
            }
        }else{
            $list=M('store')->where('store_name like "%'.$key.'%"')->limit(10)->select();
            $neirong='';
            foreach($list as $v){
                $neirong.='<li rel="'.$v['store_id'].'">'.$v['store_name'].'-'.$v['store_phone'].'</li>';
            }
        }
        echo $neirong;
    }

    public function tuihuo_edit_order(){
        $id = I('id');
        $order_sn = I('order_sn');
        $where=array();
        if($id){
            $where['id']=$id; //如果是修改。

            $orderGoods=M('return_goods a')
                ->field('a.*,b.nickname,b.company,c.store_name,c.store_phone,d.goods_name,e.nick_name as driver_name')
                ->join('ty_users b on a.user_id=b.user_id','LEFT')
                ->join('ty_store c on a.store_id=c.store_id','LEFT')
                ->join('ty_goods d on a.goods_id=d.goods_id','LEFT')
                ->join('ty_users e on a.driver_id=e.user_id','LEFT')
                ->where($where)->find();
            $spec=M('spec_goods_price')->where('`key`="'.$orderGoods['spec_key'].'"')->find();
            $orderGoods['guige']=$spec['key_name'];
        }


        if(IS_POST)
        {
            
            $fenbu_id=M('order')->where('order_sn='.I('order_sn'))->getField('fenbu_id');
            if($id){ //修改
                // M('return_goods')->where('id='.$id)->save([
                //     'order_sn'=>I('order_sn'),
                //     'goods_num'=>I('goods_num'),
                //     'user_id'=>I('user_id'),
                //     'store_id'=>I('store_id'),
                //     'driver_id'=>I('driver_id'),
                //     'remark'=>I('remark'),
                //     'fenbu_id'=>$fenbu_id,
                //     'reason'=>I('reason')
                // ]);
                
                 M('return_goods')->where('id='.$id)->save([
                    'remark'=>I('remark')
                ]);
                $this->success('修改成功','/index.php?m=admin&c=Order&a=tuihuo_edit_order&id='.$id);
            }else{
                $goods_ids=I('goods_ids');
                $pointss=I('pointss');
                $reasons=I('reasons');
                $prices=I('prices');
                $keys=I('keys');
                $goods_nums=I('goods_nums');
                $member_goods_price=I('prices');
                if($goods_ids){
                    $tui_jifen=0;
                    $order_sn = get_order_sn();
                    foreach($goods_ids as $key=>$v){
                        $order_goods=M('order_goods')->where('order_id='.I('order_id').' and spec_key="'.$keys[$key].'"')->find();
                        $return_open = M('goods g')->field('s.open_return')->join('ty_store s on s.store_id = g.store_id','LEFT')->where(['g.goods_id'=>$v])->find();
                        if($return_open['open_return'] == 0){
                            $this->error('店铺关闭了售后');
                        }
                        $return_num = M('return_goods')->where(['order_id'=>I('order_id'),'status'=>['neq',3],'goods_id'=>$v,'spec_key'=>$keys[$key]])->sum('goods_num');
                        $order = M('order o')
                        ->field('o.*,u.fenbu_id as fenbu_id')
                        ->join('ty_users u on u.user_id = o.user_id',"LEFT")
                        ->where(['o.order_id'=>I('order_id')])
                        ->find();
                        if($goods_nums[$key]>$order_goods['goods_num']-$return_num){
                            $this->error('退货数量超出订单数');
                        }
                        $tui_jifen+=$prices[$key]*$goods_nums[$key];
                        if(empty(I('driver_id'))){
                            $driver_id = M('users')->where(['nick_name'=>I('driver_name'),'is_driver'=>1])->getField('user_id');
                            if(!$driver_id){
                                $this->error('找不到司机信息');
                            }
                        }else{
                            $driver_id = I('driver_id');
                        }
                        if($order['fenbu_id'] == 0 || $order['fenbu_id'] == 42){
                            $getorder = 0;
                            $rukuTime = time();
                        }else{
                            $getorder = 2;
                            $rukuTime = '';
                        }
                        
                        
                        M('return_goods')->add([
                            'order_sn'=>I('order_sn'),
                            'return_order_sn'=>$order_sn,
                            'order_id'=>I('order_id'),
                            'fenbu_id'=>$fenbu_id,
                            'goods_id'=>$v,
                            'user_id'=>I('user_id'),
                            'store_id'=>I('store_id'),
                            'driver_id'=>$driver_id,
                            'goods_num'=>$goods_nums[$key],
                            'remark'=>I('remark'),
                            'tuihuo_time'=>time(),
                            'addtime'=>time(),
                            'member_goods_price'=>$member_goods_price[$key],
                             'points'=>$pointss[$key],
//                            'points'=>0,
                            'reason'=>$reasons[$key],
                            'spec_key'=>$keys[$key],
                            'yijia'=>$order_goods['yijia'],
                            'getorder'=>$getorder,
                            'ruku_time'=>$rukuTime
                        ]);
                    }
                    //开始退积分
                    // accountLog(I('user_id'),0,-$tui_jifen,'订单 '.I('order_sn').' 退货扣的积分！',0,I('order_id'));
                }
                update_user_level(I('user_id'));
                $this->success('添加成功','/index.php/Admin/Order/tuihuo_list2');
            }
            exit;
        }


        //echo \json_encode($orderGoods);exit;
		$this->assign('drivers',M('users')->where('is_driver=1 and is_lock=0')->select());
		$this->assign('remarks',[
			'不合适','下多/下错','对比其他商城价格偏贵','质量问题','少货','放错区域','供应商发错货/货不对板','延迟发货'
		]);
        $this->assign('order',$orderGoods);
        $this->assign('order_sn',$order_sn);
        $this->display();
    }

    public function search_goodss()
    {
        $store_id=I('store_id');
        $where = " store_id=$store_id ";//搜索所有产品
        I('intro')  && $where = "$where and ".I('intro')." = 1";
        if(!empty($_REQUEST['keywords']))
        {
            $this->assign('keywords',I('keywords'));
            $where = "$where and (goods_name like '%".I('keywords')."%' or keywords like '%".I('keywords')."%')" ;
        }

        $goodsList = M('goods')->where($where)->order('goods_id DESC')->limit(15)->select();

        foreach($goodsList as $key => $val)
        {
            $spec_goods = M('spec_goods_price')->where("goods_id = {$val['goods_id']}")->select();
            $goodsList[$key]['spec_goods'] = $spec_goods;
        }
        $this->assign('goodsList',$goodsList);
        $this->display();
    }

    public function export_tuihuo(){
        
        $timegap = I('add_time');
        $timegap2 = I('get_time');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }

        if($timegap2){
            $gap2 = explode(' - ', $timegap2);
            $begin2 = $gap2[0];
            $end2 = $gap2[1];
        }

        // 搜索条件
        $condition = array();
        if($begin && $end){
            $condition['tuihuo_time'] = array('between',"$begin,$end");
        }

        if($begin2 && $end2){
            $condition['getorder_time'] = array('between',"$begin2,$end2");
        }

        if(I('fenbu_id')!==""){
            I('fenbu_id')!=0 ? $condition['b.fenbu_id'] = I('fenbu_id') : $condition['b.fenbu_id'] = \session('fenbu_id');
        }

//		session('fenbu_id')==0 ? $condition['d.fenbu_id'] = session('fenbu_id') : false;
        I('status')!="" ? $condition['status'] = I('status') : false;
        I('biaoshi_xian')!="" ? $condition['b.biaoshi_xian'] = I('biaoshi_xian') : false;
        I('getorder')!="" ? $condition['getorder'] = I('getorder') : false;
        I('return_order_sn')!="" ? $condition['return_order_sn'] = ['like','%'.I('return_order_sn').'%'] : false;
        // I('order_sn') && $condition['_string'] = ' (remark like "%'.I('order_sn').'%")  OR (a.order_sn like "%'.I('order_sn').'%") ';
        I('consignee') && $condition['_string'] = ' (b.nickname like "%'.I('consignee').'%")  OR (b.company like "%'.I('consignee').'%") ';
        I('driver') ? $condition['f.nick_name'] = array('like','%'.trim(I('driver')).'%') : false;
        I('store') ? $condition['d.store_name'] = array('like','%'.trim(I('store')).'%') : false;
        I('print_num') ? $condition['a.print_num'] = array('gt',0) : false;
        $order_sn = I('order_sn');
        if(!empty($order_sn) && $order_sn!='undefined'){
            $condition['_string'] = ' (remark like "%'.I('order_sn').'%")  OR (a.order_sn like "%'.I('order_sn').'%") OR (a.return_order_sn like "%'.I('order_sn').'%")';
            // $condition['return_order_sn'] = ['like','%'.I('return_order_sn').'%'];
            
        }
    
        $orderList = M('return_goods a')
            ->field('a.*,b.*,c.original_img as imgs,c.goods_name,d.store_name,f.nick_name,g.fenbu_name')
            ->join('ty_users b ON a.user_id = b.user_id','LEFT')
            ->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
            ->join('ty_store d ON a.store_id = d.store_id','LEFT')
            ->join('ty_order e ON a.order_id = e.order_id','LEFT')
            ->join('ty_users f ON a.driver_id = f.user_id','LEFT')
            ->join('ty_fenbu g ON e.ufenbu_id = g.fenbu_id','LEFT')
            ->where($condition)->order('a.id desc')->select();
 

        foreach($orderList as $key=>$v){
            $orderList[$key]['key_name']=M('spec_goods_price')->where('goods_id='.$v['goods_id'].' and `key`="'.$v['spec_key'].'"')->getField('key_name');
            
            $coupom_order = M('order')->where(['order_id'=>$v['order_id']])->getField('coupon_price');
            $coupom_total_amount = M('order')->where(['order_id'=>$v['order_id']])->getField('total_amount');
             $couponreturngoods = 0;
        // $coupom_order = 0;
            if($coupom_order > 0){
                $Proportion = (($v['member_goods_price']+$v['yijia']) * $v['goods_num'])/$coupom_total_amount;
                //算出优惠金额
                $couponreturngoods += geshi($Proportion*$coupom_order);
            }else{
                $couponreturngoods = 0;
            }
      
            $orderList[$key]['coupon_price'] = $couponreturngoods;

        }
        // dump($orderList);
        // die;
        $strTable ='<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">商家</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">单号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">线路</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">原单号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">分部</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">司机</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">买家</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">单价</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">数量</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单价</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">优惠价</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">平台扣点</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">应扣金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">取货状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">创建时间</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">审核时间</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">取货时间</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">备注</td>';
        $strTable .= '</tr>';

        
        foreach($orderList as $k=>$val){
            $dsprice=(float)($val['member_goods_price']+$val['yijia'])*(float)$val['goods_num']; //订单价
            $ptprice=($dsprice-$val['yijia'])*($val['points']/100); //平台价
            $ptprices=$dsprice-$ptprice;
            if($val['status'] == 2){
                $zhuangtai = "已扣费";
            }elseif ($val['status'] == 1){
                $zhuangtai = "已审核";
            }elseif ($val['status'] == 3){
                $zhuangtai = "已取消";
            }else{
                $zhuangtai = "未审核";
            }
            $val['nick_name'] =  $val['nick_name'] ?? '没找到司机';

            if($val['getorder'] == 2){
                $val['getorder'] = '未入库';
            }elseif($val['getorder'] == 0){
                $val['getorder'] = "未取货";
            }else{
                $val['getorder']="已取货";
            }

            // unset($orderGoods);
            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['store_name'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['return_order_sn'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;color:red">&nbsp;'.$val['biaoshi_xian'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_sn'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['fenbu_name'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['nick_name'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['goods_name'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['company'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.($val['member_goods_price']+$val['yijia']).' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['goods_num'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$dsprice.'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['coupon_price'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$ptprice.'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;color:red">'.$ptprices.'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;color:red">'.$val['getorder'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$zhuangtai.'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.\date('Y-m-d H:i:s',$val['addtime']).' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['check_time'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['getorder_time'].' </td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['remark'].'</td>';
            $strTable .= '</tr>';
        }
        $strTable .='</table>';
        // unset($orderList);

        downloadExcel($strTable,'ordertuihuo');
        exit();
    }


    public function ruku_all()
    {
        $order_id = I('order_id');
        $order = M('order')->where(['order_id'=>$order_id,'order_status'=>['in','0,1']])->find();
        if($order  && $order['jian_count'] > 0){
            $order_jian =  M('order_jian')->where(['order_id'=>$order_id])->find();
            if(!$order_jian){
                echo json_encode(['status'=>0,'msg'=>'请重新更改标签数']);exit;
            }
            M('order_jian')->where(['order_id'=>$order_id])->save(['pda_name_ruku'=>'yc-88','status_r'=>1,'ruku_time'=>time()]);
            M('order')->where(['order_id'=>$order_id])->save(['order_status'=>1,'shipping_status'=>1,'ruku_last_time'=>time(),'ruku_count'=>$order['jian_count']]);
            M('users_price')->where('order_id='.$order_id)->setField(['status'=>1]);
            echo json_encode(['status'=>1,'msg'=>'操作成功']);exit;
        }else{
            echo json_encode(['status'=>0,'msg'=>'操作失败,订单状态错误']);exit;
        }

    }
    public function chuku_all()
    {
        //['biaoshi_xian'=>$user['biaoshi_xian'],'is_driver'=>1]
        $order_id = I('order_id');
        $driver_name = I('driver_name');
        $order = M('order')->where(['order_id'=>$order_id,'order_status'=>['in','0,1']])->find();
        $driver = M('users')->where("is_driver = 1 and nick_name = '".$driver_name."' ")->order('user_id desc')->getField('user_id');
        if($order  && $order['jian_count'] > 0 && $driver){
//            $xianlu_flag = M('users')->where(['user_id'=>$order['user_id'],'biaoshi_xian'=>$driver['biaoshi_xian']])->count();
//            if($xianlu_flag){
                M('order_jian')->where(['order_id'=>$order_id])->save(['pda_name_chuku'=>'yc-88','status_c'=>1,'chuku_time'=>time()]);
                if($order['chuku_last_time']){
                    if($order['chuku_count'] != $order['ruku_count']){
                        M('order')->where(['order_id'=>$order_id])->save(['chuku_count'=>$order['jian_count'],'driver_id'=>$driver,'pda_qdzt'=>0]);
                    }
                }else{
                    if($order['chuku_count'] != $order['ruku_count']){
                        M('order')->where(['order_id'=>$order_id])->save(['chuku_last_time'=>time(),'chuku_count'=>$order['jian_count'],'driver_id'=>$driver,'pda_qdzt'=>0]);
                    }
                }
    
                echo json_encode(['status'=>1,'msg'=>'操作成功']);exit;
//            }else{
//                echo json_encode(['status'=>0,'msg'=>'操作失败,该司机与订单线路不匹配']);exit;
//            }
        }else{
            echo json_encode(['status'=>0,'msg'=>'操作失败,没有找到对应的司机']);exit;
        }

    }
    public function batch_chuku_all()
    {  //['biaoshi_xian'=>$user['biaoshi_xian'],'is_driver'=>1]
        $order_id = I('order_id');
        $driver_name = I('driver_name');
        $order_list = M('order')->where(['order_id'=>['in',$order_id],'order_status'=>['in','0,1']])->select();
        $driver = M('users')->where("is_driver = 1 and nick_name = '".$driver_name."' ")->order('user_id desc')->find();
        if(!empty($driver)){
            foreach($order_list as $order){
//                $xianlu_flag = M('users')->where(['user_id'=>$order['user_id'],'biaoshi_xian'=>$driver['biaoshi_xian']])->count();
//                if($xianlu_flag){
                    if($order  && $order['jian_count'] > 0){
                        M('order_jian')->where(['order_id'=>$order['order_id']])->save(['pda_name_chuku'=>'yc-88','status_c'=>1,'chuku_time'=>time()]);
                        if($order['chuku_last_time']){
                            if($order['chuku_count'] != $order['ruku_count']){
                                M('order')->where(['order_id'=>$order['order_id']])->save(['chuku_count'=>$order['jian_count'],'driver_id'=>$driver['user_id'],'pda_qdzt'=>0]);
                            }
                        }else{
                            if($order['chuku_count'] != $order['ruku_count']){
                                M('order')->where(['order_id'=>$order['order_id']])->save(['chuku_last_time'=>time(),'chuku_count'=>$order['jian_count'],'driver_id'=>$driver['user_id'],'pda_qdzt'=>0]);
                            }
                        }
                    }else{
                        echo json_encode(['status'=>0,'msg'=>'操作失败,订单件数错误']);exit;
                    }
//                }else{
//                    echo json_encode(['status'=>0,'msg'=>'操作失败,该司机与订单线路不匹配']);exit;
//                }
            }
            echo json_encode(['status'=>1,'msg'=>'操作成功']);exit;
        }else{
            echo json_encode(['status'=>0,'msg'=>'操作失败,没有找到对应的司机']);exit;
        }

    }

    /**
     * 批量修改司机
     * @return void
     */
    public function batch_edit_driver()
    {
        $order_id = I('order_id');
        $driver_name = I('driver_name');
        $order_list = M('order')->where(['order_id'=>['in',$order_id],'order_status'=>['in','0,1']])->select();
        $driver = M('users')->where("is_driver = 1 and nick_name = '".$driver_name."' ")->order('user_id desc')->find();
        if(!empty($driver)){
            foreach($order_list as $order){
                M('order')->where(['order_id'=>$order['order_id']])->save(['driver_id'=>$driver['user_id']]);
            }
            echo json_encode(['status'=>1,'msg'=>'操作成功']);exit;
        }else{
            echo json_encode(['status'=>0,'msg'=>'操作失败,没有找到对应的司机']);exit;
        }

    }
    
     /**
     * 批量修改司机订单不出库
     * @return void
     */
    public function act_edit_notchuku()
    {
        $order_id = I('order_id');
        $order_list = M('order')->where(['order_id'=>['in',$order_id],'order_status'=>['in','0,1']])->select();
        if(!empty($order_list)){
            foreach($order_list as $order){
                //不在确认收款表就可以修改
                $orderData = M('order_statis')->where(['order_sn'=>$order['order_sn']])->find();
                if(empty($orderData)){
                    M('order')->where(['order_id'=>$order['order_id']])->save(['chuku_last_time'=>'','chuku_count'=>0]);
                    M('order_jian')->where(['order_id'=>$order['order_id']])->save(['chuku_time'=>'','status_c'=>0,'pda_name_chuku'=>'']);
                }
            }
            echo json_encode(['status'=>1,'msg'=>'操作成功']);exit;
        }else{
            echo json_encode(['status'=>0,'msg'=>'操作失败,没有找到对应的司机']);exit;
        }
    }

    /**
     * 修改入出库时间
     */
    public function edit_ku_time()
    {
        $order_id = I('order_id');
        $type = I('type');
        $time = I('val');

        if($time){
            if($type == 'ruku_last_time'){
                M('order_jian')->where(['order_id'=>$order_id])->save(['ruku_time'=>strtotime($time)]);
                M('order_jian')->where(['order_id'=>$order_id])->save(['pda_name_ruku'=>'yc-88','status_r'=>1,'ruku_time'=>strtotime($time)]);
            }elseif($type == 'chuku_last_time'){
                M('order_jian')->where(['order_id'=>$order_id])->save(['chuku_time'=>strtotime($time)]);
                M('order_jian')->where(['order_id'=>$order_id])->save(['pda_name_chuku'=>'yc-88','status_c'=>1,'chuku_time'=>strtotime($time)]);
            }elseif ($type == 'duizhang_sn'){
                M('order')->where(['order_id'=>$order_id])->save(['pda_qdzt'=>0,'admin_note'=>null]);
            }
            M('order')->where(['order_id'=>$order_id])->save([$type=>strtotime($time)]);
        }

    }
}
